David Janes' Code Weblog

October 23, 2011

Automatically Binding Resources to Fields in Android Applications

android,code fragments,java · admin · 4:53 pm ·

AKA I’m as mad as hell at Java and not taking it any more.

Here’s how I’ve been getting access to various UI resources in my Android applications. Almost certainly, you’re doing the same thing too.


<TextView android:id="@+id/title" ... />


TextView title = (TextView) parent.findViewById(R.id.title);

Over and over for as many UI elements as I need to access. To hell with that.

Here’s my new method of doing this

First, give the ID and the Fields the same name:


<TextView android:id="@+id/uiTitleTextView" ... />


public TextView uiTitleTextView;

Note that that’s a class field — it’s not in the method, and it must be public Then in onCreate I just do this:


And that’s it: every field just gets wired up.

The Code

Here’s The Magic for UIHelper.java:

static public void bindViews(Activity _activity)
  Field[] instance_fields = _activity.getClass().getDeclaredFields();
  for (Field instance_field : instance_fields) {
    if (!View.class.isAssignableFrom(instance_field.getType())) {
    try {
      Field id_field = R.id.class.getField(instance_field.getName());
      int r = id_field.getInt(R.id.class);
      View view = _activity.findViewById(r);
      if (view == null) {
        LogHelper.debug(true, _activity, 
          "Field expected in Layout but not found", "name=", 
      instance_field.set(_activity, view);
    } catch (NoSuchFieldException x) {
      LogHelper.debug(true, _activity, 
        "Field expected in R.id but not found", "name=", 
    } catch (IllegalAccessException x) {
      LogHelper.debug(true, _activity, 
        "Can't set R.id", "name=", 
        instance_field.getName(), x);


  1. […] When developing Android applications, binding resources to end method calls is even more annoying than binding resources to variables. […]

  2. florin · 2012-12-12 14:55


    This helped me, thanks!

RSS feed for comments on this post.

Sorry, the comment form is closed at this time.

Powered by WordPress