Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: automatically make variables for all IDs in xml

Tags:

I noticed one of the most tedious parts of Android development is the layout design, even with layout builder.

After setting up the graphics, then the layout, making variable associations with the layout elements is very tedious, such as ImageButton myButton = (ImageButton)findViewById(R.id.myButton);

in larger layouts, these can get tedious to keep track of (recalling the names of the elements) and then the need to add more variables in any kind of order gets frustrating.

To slightly mitigate this, it would be very convenient if all of the IDs I declared in the XML were automatically associated with their proper variables, and all of those datatypes were already included in that class

Is there something that already does this?

for instance if I write

 <ImageButton android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@drawable/myButton" android:id="@+id/myButton"></ImageButton>

then I would like the classes which include this layout to already have

 import android.ImageButton;

 ImageButton myButton;

 myButton = (ImageButton)findViewById(R.id.myButton);

is this a setting or a feature to request? I am using the Eclipse IDE and it would be very convenient

like image 599
CQM Avatar asked Aug 01 '11 21:08

CQM


2 Answers

I made a tool to automatically generate the Java code for tying layout XML's and program logic together.

Basically it takes an XML layout, and generates all the necessary Java code for you in an instant. There is support for basic member variables, ViewHolder pattern, ArrayAdapter, CursorAdapter and RoboGuice code types.

You can find it here: Android Layout Finder | Buzzing Android

like image 126
JesperB Avatar answered Sep 22 '22 17:09

JesperB


Try using Android Annotations. It provides useful annotations to replace boilerplate code.

For instance, see @ViewById documentation: just declare the fields annotated

@ViewById
EditText myEditText;

@ViewById(R.id.myTextView)
TextView textView;

It replaces

EditText myEditText;

TextView textView;
@Override
public void onCreate(Bundle savedInstanceState) {
    [...]
    myEditText = (EditText) findViewById(R.id.myEditText);
    textView = (TextView) findViewById(R.id.myTextView);
}
like image 15
Andy Avatar answered Sep 21 '22 17:09

Andy