AndroidAnnotation
目录(?)[+]
- Injecting Views视图注入
- ViewById
- AfterViews
Injecting Views视图注入
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.
@ViewById
注解标识一个activity字段应该和布局中的一致的视图组件绑定在一起。就和调用
findViewById()
方法一样。view id可以在注解参数中添加,比如
@ViewById(R.id.myTextView)
。假如没有设置view id,将默认使用字段名。这个字段不能是private类型的,一般使用默认类型或者protected类型。
Usage example:用法:
@EActivity public class MyActivity extends Activity { // Injects R.id.myEditText@ViewByIdEditText myEditText;@ViewById(R.id.myTextView)TextView textView; }
@AfterViews
The
@AfterViews
annotation indicates that a
method should be called after the views binding has happened.
@AfterViews
注解标识在视图绑定操作发生后,有个方法需要被调用,一般可以使用init方法名。
When
onCreate()
is called,@ViewById
fields are not set yet. Therefore, you can use@AfterViews
on methods to write code that depends on views.当onCreate()
方法调用后,@ViewById
字段还没有设置好。因此,你可以用@AfterViews
注解绑定的方法添加处理视图相关的代码。
Usage example:用法:
@EActivity(R.layout.main) public class MyActivity extends Activity { @ViewByIdTextView myTextView;@AfterViewsvoid 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()
:
你可以用
@AfterViews
注解多个方法。不要忘记在
onCreate()
方法中
不能
使用任何视图字段。
@EActivity(R.layout.main) public class MyActivity extends Activity { @ViewByIdTextView myTextView;@Overridepublic 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:
回想一下,注入总是以最快的速度完成。因此,在
@AfterViews
方法中使用任何不需要设置视图(像
@AfterViews
要做的)注解字段,比如
@Extra 或者 @InstanceState,都是安全的。所以,你可以放心地假设这些字段在加了
@AfterViews
注解的方法中初始化值是安全的。
@EActivity(R.layout.main) public class MyActivity extends Activity { @ViewByIdTextView myTextView;@InstanceStateInteger textPosition;@AfterViewsvoid updateTextPosition() { myTextView.setSelection(textPosition); //Sets the cursor position of myTextView} [...] // The remaining code must keep textPosition updated