Skip to content
pyricau edited this page Jan 14, 2012 · 4 revisions

Since AndroidAnnotations 1.0

@ViewById

The @ViewById annotation indicates that an activity field should be bound with the corresponding View component from the layout. It is the same as calling the findViewById() method. The view id can be set in the annotation parameter, ie @ViewById(R.id.myTextView). If the view id is not set, the name of the field will be used. The field must not be private.

Usage example:

@EActivity
public class MyActivity extends Activity {

  // Injects R.id.myEditText
  @ViewById
  EditText myEditText;

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

@AfterViews

The @AfterViews annotation indicates that a method should be called after the views binding has happened.

When onCreate() is called, @ViewById fields are not set yet. Therefore, you can use @AfterViews on methods to write code that depends on views.

Usage example:

@EActivity(R.layout.main)
public class MyActivity extends Activity {

    @ViewById
    TextView myTextView;

    @AfterViews
    void updateTextWithDate() {
        myTextView.setText("Date: " + new Date());
    }
[...]

You can annotate multiple methods with @AfterViews. Don't forget that you should not use any view field in onCreate():

@EActivity(R.layout.main)
public class MyActivity extends Activity {

    @ViewById
    TextView myTextView;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        // DON'T DO THIS !! It will throw a NullPointerException, myTextView is not set yet.
        // myTextView.setText("Date: " + new Date());
    }
[...]

Using AndroidAnnotations

Questions?

Enjoying AndroidAnnotations

Improving AndroidAnnotations

Clone this wiki locally