[2] use of the Injection framework RoboGuice: (Your First View Injection) and roboguiceinjection
In the previous article, we briefly introduced the use of RoboGuice ([1] use of the injection framework RoboGuice :( A brief example of what RoboGuice does )), today, let's take a look at the usage of the View annotation.
To use the View annotation in an Activity, you must perform the following three steps:
①: The custom Activity inherits RoboActivity.
②: Set content View
③: Use @ InjectView to annotate the View Control
Next, let's take a detailed look at the usage:
(1) Create an Activity that inherits from RoboActivity:
public class MyActivity extends RoboActivity { ... }Then add a layout to the Activity:
// Override onCreate() and call setContentView() public class MyActivity extends RoboActivity { @Override protected void onCreate( Bundle savedState ) { setContentView(R.layout.myactivity_layout); } }In the layout file myactivity_layout.xml, the ID of the control TextView is defined as text. Now you can annotate the view control and use it directly without using findViewByID for initialization.
public class MyActivity extends RoboActivity { @InjectView(R.id.text1) TextView textView; @Override protected void onCreate( Bundle savedState ) { setContentView(R.layout.myactivity_layout); textView.setText("Hello!"); } }Now, a simple View annotation example is complete. It's easy. Does it save a lot of effort.
(2) contentview Annotation
The View annotation is demonstrated above. The layout settings can also be implemented through annotation, as shown below:
@ContentView(R.layout.myactivity_layout) public class MyActivity extends RoboActivity { @InjectView(R.id.text1) TextView textView; @Override protected void onCreate( Bundle savedState ) { textView.setText("Hello!"); } }
(3) Of course, in addition to the preceding view control and contentview annotation, we can also annotate any type of view, or even custom View.