Android:自动为xml中的所有ID创建变量

CQM*_*CQM 17 xml layout android convenience-methods

我注意到Android开发中最繁琐的部分之一是布局设计,即使是布局构建器也是如此.

在设置图形之后,布局,与布局元素进行变量关联是非常繁琐的,例如 ImageButton myButton = (ImageButton)findViewById(R.id.myButton);

在较大的布局中,这些可能变得乏味以便跟踪(回忆元素的名称),然后需要以任何类型的顺序添加更多变量令人沮丧.

为了稍微缓解这种情况,如果我在XML中声明的所有ID都与其正确的变量自动关联,并且所有这些数据类型都已包含在该类中,那将非常方便

有什么东西已经做到了吗?

例如,如果我写

 <ImageButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/myButton" android:id="@+id/myButton"></ImageButton>
Run Code Online (Sandbox Code Playgroud)

那么我想包含这种布局的类已经有了

 import android.ImageButton;

 ImageButton myButton;

 myButton = (ImageButton)findViewById(R.id.myButton);
Run Code Online (Sandbox Code Playgroud)

这是要求的设置或功能吗?我正在使用Eclipse IDE,这将非常方便

Jes*_*erB 32

我创建了一个工具来自动生成Java代码,用于将布局XML和程序逻辑绑定在一起.

基本上它需要XML布局,并立即为您生成所有必需的Java代码.支持基本成员变量,ViewHolder模式,ArrayAdapter,CursorAdapter和RoboGuice代码类型.

你可以在这里找到它:Android Layout Finder | 嗡嗡的Android


And*_*ndy 14

尝试使用Android Annotations.它提供了有用的注释来替换样板代码.

例如,请参阅@ViewById 文档:只需声明注释的字段

@ViewById
EditText myEditText;

@ViewById(R.id.myTextView)
TextView textView;
Run Code Online (Sandbox Code Playgroud)

它取代了

EditText myEditText;

TextView textView;
@Override
public void onCreate(Bundle savedInstanceState) {
    [...]
    myEditText = (EditText) findViewById(R.id.myEditText);
    textView = (TextView) findViewById(R.id.myTextView);
}
Run Code Online (Sandbox Code Playgroud)