在Android應用程序中,很多地方需要引用到Context對象(Activity,Application,Service等)。Roboguice 使得引用Context對象變得非常容易。
可以參見下面例子,這裡定義一個不在Activity中的類ContextInfo,需要引用Context對象:
[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;
}
}
需要應用Context對象時,使用@Inject 標記,Roboguice會自動註入所需Context對象。
定義一個InjectContextDemo,使用一個TextView來顯示ContextInfo的getPackageName內容。
[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());
}
}
在InjectContextDemo中定義一個InjectContextDemo,也使用@Inject 通知Roboguice自動創建它的一個實例。Roboguice在創建這個對象時,調用其Injectable 構造函數(參見Android RoboGuice 使用指南(10): Just-in-time Bindings/kf/201205/130101.html ),自動傳入Context對象。
如果需要應用Application對象,可以將構造函數改為
[java] @Inject
ContextInfo(RoboguiceDemoApplication context){
this.context=context;
}
@Inject
ContextInfo(RoboguiceDemoApplication context){
this.context=context;
}
或引用Activity
[java] @Inject
ContextInfo(Activity context){
this.context=context;
}
@Inject
ContextInfo(Activity context){
this.context=context;
}
本例下載:http://up.aiwalls.com/2012/0507/20120507110106855.zip
摘自 引路蜂移動軟件