> Android在线手册 > Android RoboGuice 使用指南(15):Inject Context

在Android应用程序中,很多地方需要引用到Context对象(Activity,Application,Service等)。Roboguice 使得引用Context对象变得非常容易。

可以参见下面例子,这里定义一个不在Activity中的类ContextInfo,需要引用Context对象:

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内容。

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 ),自动传入Context对象。

Android RoboGuice 使用指南(15):Inject Context如果需要应用Application对象,可以将构造函数改为

@Inject
 ContextInfo(RoboguiceDemoApplication context){
 this.context=context;
}

或引用Activity

@Inject 
 ContextInfo(Activity context){
  this.context=context;	
}