In Android applications, Context objects (such as Activity, Application, and Service) need to be referenced in many places ). Roboguice makes it easy to reference Context objects.
You can refer to the following example to define a ContextInfo class not in the Activity. You need to reference the Context object:
[Java] class ContextInfo {
Final Context context;
@ Inject
ContextInfo (Context context ){
This. context = context;
}
String getPackageName (){
Return context. getApplicationInfo (). packageName;
}
}
Class ContextInfo {
Final Context context;
@ Inject
ContextInfo (Context context ){
This. context = context;
}
String getPackageName (){
Return context. getApplicationInfo (). packageName;
}
}
When you need to apply the Context object, use the @ Inject mark. Roboguice automatically injects the required Context object.
Define an InjectContextDemo and use a TextView to display the getPackageName content of ContextInfo.
[Java] public class InjectContextDemo extends RoboActivity {
@ InjectView (R. id. textview) TextView textView;
@ Inject ContextInfo contextInfo;
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. injectcontext );
TextView. setText (contextInfo. getPackageName ());
}
}
Public class InjectContextDemo extends RoboActivity {
@ InjectView (R. id. textview) TextView textView;
@ Inject ContextInfo contextInfo;
@ Override
Public void onCreate (Bundle savedInstanceState ){
Super. onCreate (savedInstanceState );
SetContentView (R. layout. injectcontext );
TextView. setText (contextInfo. getPackageName ());
}
}
Define an InjectContextDemo in InjectContextDemo, and notify Roboguice to automatically create an instance using @ Inject. When creating this object, Roboguice calls its Injectable Constructor (see Android RoboGuice User Guide (10): Just-in-time Bindingshttp: // www.bkjia.com/kf/201205/130101.html) to automatically pass in the Context object.
To apply the Application object, you can change the constructor
[Java] @ Inject
ContextInfo (RoboguiceDemoApplication context ){
This. context = context;
}
@ Inject
ContextInfo (RoboguiceDemoApplication context ){
This. context = context;
}
Or reference Activity
[Java] @ Inject
ContextInfo (Activity context ){
This. context = context;
}
@ Inject
ContextInfo (Activity context ){
This. context = context;
}
Download this example: http://www.bkjia.com/uploadfile/2012/0507/20120507110106855.zip
Excerpted from the mobile app