views

Rss feed of the tag

If you don't find Views by id, Views will find you

Written by Xavier Gouchet - 11 july 2012 - no comments

One of the first thing an Android developer has to learn, it's to match Views declared in an XML layout to fields in the Activity class. Something that looks like this, repeated for all the views you need to manipulate from your activity.


class MyActivity extends Activity {

    private Button myButton; 

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_sample_views);
        myButton = (Button) findViewById(R.id.myButtonId);
    }
}

Now this can be quite troublesome, and could be automatized. So here it is, a class to help you fill in your fields. You can download it or fork it directly from GitHub.

The use can be pretty simple, and is just two lines, whatever the number of views you may have :


class MyActivity extends Activity {

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.my_layout);

        ViewFieldMatcher matcher = new ViewFieldMatcher(R.id.class);
        matcher.matchViews(findViewById(android.R.id.content), this);
    }

This code will automatically match any view to the corresponding field, matching the id name to the field's name.