当前位置:操作系统 > 安卓/Android >>

Android RoboGuice使用指南(15):Inject Context

在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 Bindingshttp://www.zzzyk.com/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;
}

本例下载:/2012/0507/20120507110106855.zip




摘自 引路蜂移动软件
 

补充:移动开发 , Android ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,