Search code examples
androidxmllayoutconvenience-methods

Android: automatically make variables for all IDs in xml


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


Solution

  • 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);
    }