-
Notifications
You must be signed in to change notification settings - Fork 0
Injecting Views
Since AndroidAnnotations 1.0
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:
@ViewById
EditText myEditText;
@ViewById(R.id.myTextView)
TextView textView;Equivalent boilerplate code:
EditText myEditText;
TextView textView;
@Override
public void onCreate(Bundle savedInstanceState) {
[...]
myEditText = (EditText) findViewById(R.id.myEditText);
textView = (TextView) findViewById(R.id.myTextView);
}The @AfterViews annotation indicates that a method should be called after the views binding has happened.
When
onCreate()is called,@ViewByIdfields are not set yet. Therefore, you can use@AfterViewson 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());
}
[...]Equivalent boilerplate code:
public class MyActivity extends Activity {
TextView myTextView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
myTextView = (TextView) findViewById(R.id.myTextView);
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());
}
[...]14/06/2012 The 2.6 release is out
- Get started!
- Cookbook, full of recipes
- List of all available annotations
- Release Notes
- Examples
- Read the FAQ
- Join the Mailing list
- Create an issue
- Tag on Stack Overflow