-
Notifications
You must be signed in to change notification settings - Fork 5
Injection inside Views
InjectView automatically injects all views & fragments inside a view.
The only things to remember is WHEN the injection takes place.
The injection of views (no fragments can be injected inside a view) will take place right after the call to super.onFinishInflate inside your custom method onFinishInflate.
In Android, Views have 3 different possible constructors :
- View(Context)
- View(Context context, AttributeSet attrs)
- View(Context context, AttributeSet attrs, int defStyleAttr)
The first constructor is usually called when creating a view by code, the 2 last constructors are used internally by Android when creating a view from a XML layout.
In Android, onFinishInflate is called automatically when inflating a view from XML (by the 2 last constructors). But it is not triggered automatically when using the first constructor.
Thus, we recommend to adopt the following pattern to create views : define all possible constructors so that your view can be created from code & XML. And call onFinishInflate manually from inside the first constructor :
public class MyView extends View {
@InjectView(R.id.textView) private TextView view;
public MyView(Context context) {
super(context);
onFinishInflate();
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public onFinishInflate() {
super.onFinishInflate()
//injection takes place here,
//right after the call to super.onFinishInflate
view.setText("foo");
}
}Note : if you don't provide any custom onFinishInflate method, InjectView will add one to your view, calling super.onFinishInflate and performing the injection of views.
Views annotated using @InjectView can have any visibility modifier, including private.
Views can be identified using an id (annotation default value) or a tag (using tag parameter of the annotation).