In Android applications, many places need to refer to context objects (activity, application,service, etc.). Roboguice makes referencing the context object very easy.
See the following example, where you define a class contextinfo that is not in the activity, and you need to reference the context object:
Class contextinfo{
final context context;
@Inject
ContextInfo (context context) {
This.context=context
}
String Getpackagename () {return
context.getapplicationinfo (). PackageName;
}
}
When a context object needs to be applied, the @inject tag is used, and roboguice automatically injects the required context object.
Define a Injectcontextdemo, using a textview to display the getpackagename content of the ContextInfo.
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 ());
}
A injectcontextdemo is defined in Injectcontextdemo, and an instance of it is automatically created using the @inject notification Roboguice. Roboguice when this object is created, it invokes its injectable constructor (see Android Roboguice Use guide: Just-in-time bindings) to automatically pass in the context object.
If you need to apply the Application object, you can change the constructor to
@Inject
ContextInfo (roboguicedemoapplication context) {
This.context=context
}
or reference activity
@Inject
ContextInfo (activity context) {
This.context=context
}
This example downloads: Http://www.imobilebbs.com/download/android/roboguice/InjectContextDemo. Zip
View a full set of articles: Http://www.bianceng.cn/OS/extra/201301/34950.htm