Injecting Views - PerfectCarl/androidannotations GitHub Wiki
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());
}
[...]
Recall that injection is always made as soon as possible. Therefore, it's safe to use any field annotated, e.g., with @Extra or @InstanceState in @AfterViews methods as these tags don't require any view to be set (as @AfterViews do). Therefore you can safely assume that such fields will be already initialized with their intended values in methods annotated with @AfterViews:
@EActivity(R.layout.main)
public class MyActivity extends Activity {
@ViewById
TextView myTextView;
@InstanceState
Integer textPosition;
@AfterViews
void updateTextPosition() {
myTextView.setSelection(textPosition); //Sets the cursor position of myTextView
}
[...] // The remaining code must keep textPosition updated.