在 Android 應(yīng)用程序中,很多地方需要引用到 Context 對象(Activity,Application,Service 等)。Roboguice 使得引用 Context 對象變得非常容易。
可以參見下面例子,這里定義一個(gè)不在 Activity 中的類 ContextInfo,需要引用 Context 對象:
class ContextInfo{
final Context context;
@Inject
ContextInfo(Context context){
this.context=context;
}
String getPackageName(){
return context.getApplicationInfo().packageName;
}
}
需要應(yīng)用 Context 對象時(shí),使用 @Inject 標(biāo)記,Roboguice 會自動注入所需 Context 對象。
定義一個(gè) InjectContextDemo,使用一個(gè) TextView 來顯示 ContextInfo 的 getPackageName 內(nèi)容。
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());
}
}
在 InjectContextDemo 中定義一個(gè) InjectContextDemo,也使用 @Inject 通知 Roboguice 自動創(chuàng)建它的一個(gè)實(shí)例。Roboguice 在創(chuàng)建這個(gè)對象時(shí),調(diào)用其 Injectable 構(gòu)造函數(shù)(參見 Android RoboGuice 使用指南(10): Just-in-time Bindings ),自動傳入 Context 對象。
http://wiki.jikexueyuan.com/project/android-roboguice/images/16.png" alt="" />
如果需要應(yīng)用 Application 對象,可以將構(gòu)造函數(shù)改為
@Inject
ContextInfo(RoboguiceDemoApplication context){
this.context=context;
}
或引用Activity
@Inject
ContextInfo(Activity context){
this.context=context;
}