In the previous article, we briefly introduced the use of roboguice ([10] use of the injection framework roboguice :( your first testcase). Today, let's take a look at custom view injection (custom view ).
Before starting this article, you must familiarize yourself with normal Java object injection (click to enter ). In roboguice 3.0, you also perform such operations on custom views.
class MyView extends View { @Inject Foo foo; @InjectView(R.id.my_view) TextView myView; public MyView(Context context) { inflate(context,R.layout.my_layout, this); RoboGuice.getInjector(getContext()).injectMembers(this); } public MyView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); inflate(context,R.layout.my_layout, this); RoboGuice.getInjector(getContext()).injectMembers(this); } public MyView(Context context, AttributeSet attrs) { super(context, attrs); inflate(context,R.layout.my_layout, this); RoboGuice.getInjector(getContext()).injectMembers(this); } @Override public void onFinishInflate() { super.onFinishInflate(); //All injections are available from here //in both cases of XML and programmatic creations (see below) myView.setText(foo.computeFoo()); }}
In Android, you can create a view in two ways:
①: Automatically load data from XML
②: The program method is created using new customview (context ).
With roboguice 3.0, you must ensure that the injection from roboguice is obtained through explicit injection under any circumstances.
In roboguice 3.1, there are some differences:
Roboguice 3.1 is loaded completely through XML and is automatically injected into all the child controls in the view. During XML loading, note that the onfinishinflate () method is automatically called back. However, if you provide additional constructor, You need to inject it through roboguice.
In the latter case, the onfinishinflate () method is called at the end of the constructor. If you want to use the roboguice template, you can better use this callback method to process all constructors. Your custom views will be injected.
The following is an example:
class MyView extends View { @Inject Foo foo; @InjectView(R.id.my_view) TextView myView; public MyView(Context context) { inflate(context,R.layout.my_layout, this); RoboGuice.getInjector(getContext()).injectMembers(this); onFinishInflate(); } public MyView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); inflate(context,R.layout.my_layout, this); } public MyView(Context context, AttributeSet attrs) { super(context, attrs); inflate(context,R.layout.my_layout, this); } @Override public void onFinishInflate() { super.onFinishInflate(); //All injections are available from here //in both cases of XML and programmatic creations (see below) myView.setText(foo.computeFoo()); }}
[11] use of the injection framework roboguice: (your first injection into a custom View class)