Android RoboGuice 使用指南3

Android RoboGuice 使用指南(14):Inject View

在例子Android RoboGuice 使用指南(2):第一个例子Hello World 介绍了使用Roboguice开发的基本步骤:

  1. 创建一个RoboApplication 的子类GuiceApplication,GuiceApplication为Appliacation的子类,修改AndroidManifest.xml,将Application 的name 指向这个类。
  2. 将原先由Activity派生的类基类改为RoboActivity(或其它相关Activity).
  3. 如果有需要的话在AbstractAndroidModule 中重载configuatation方法定义bindings.

如果不使用Roboguice,如果Activity中需要访问定义在Layout中的某个View,一般需要使用findViewById 来查找对应的View,并将它强制转换为对应的类,如果需要访问的View很多,重复的代码就非常繁琐。

如果使用Roboguice 的Inject View ,代码就简洁易读多了,@Inject View的基本用法如下:

@InjectView (R.id.xxx)  ViewType  viewInstance;

  • R.id.xxx 为所需View定义在Layout中的id  ,如R.id.textview1
  • ViewType 为所需View的类型,如TextView
  • viewInstance 为变量名。

我们定义一个injectview.xml ,如下:

<?xml version=”1.0″ encoding=”utf-8″?>
<LinearLayout
xmlns:android=”http://schemas.android.com/apk/res/android”
android:orientation=”vertical”
android:layout_width=”match_parent”
android:layout_height=”match_parent”>

<TextView 
android:id=”@+id/textview1″
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”@string/injectview”
/>

<TextView 
android:id=”@+id/textview2″
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”@string/injectview”
/>

<TextView 
android:id=”@+id/textview3″
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”@string/injectview”
/>

<TextView 
android:id=”@+id/textview4″
android:layout_width=”fill_parent”
android:layout_height=”wrap_content”
android:text=”@string/injectview”
/>

<Button android:id=”@+id/button”
android:layout_width=”wrap_content”
android:layout_height=”wrap_content”
android:layout_gravity=”center_vertical”
android:text=”@string/clickmebutton”/>

</LinearLayout>

定义了4个TextView和一个Button,看看如何使用InjectView来访问这些View:

1 public class InjectViewDemo extends RoboActivity {
2  
3  @InjectView (R.id.button) Button goButton;
4  @InjectView (R.id.textview1) TextView textView1;
5  @InjectView (R.id.textview2) TextView textView2;
6  @InjectView (R.id.textview3) TextView textView3;
7  @InjectView (R.id.textview4) TextView textView4;
8  
9  @Override
10  public void onCreate(Bundle savedInstanceState) {
11  super.onCreate(savedInstanceState);
12  
13  setContentView(R.layout.injectview);
14  goButton.setOnClickListener(mGoListener);
15  }
16  
17  private OnClickListener mGoListener = new OnClickListener()
18  {
19  public void onClick(View v)
20  {
21  textView1.setText("Clicked");
22  textView2.setText("Clicked");
23  textView3.setText("Clicked");
24  textView4.setText("Clicked");
25  }
26  };
27 }

无需使用findViewById 来为每个变量(如textview1)赋值,只需使用@InjectView标记,赋值的工作都由Roboguice 来完成,程序只需向Roboguice说“给我某个View”,Roboguice就通过Dependency Injection传给应用程序所需View的实例对象。代码比不使用Roboguice时简洁多了。

本例下载

 
 

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

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

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

1 class ContextInfo{
2  
3  final Context context;
4  @Inject
5  ContextInfo(Context context){
6  this.context=context;
7  }
8  
9  String getPackageName(){
10  return context.getApplicationInfo().packageName;
11  }
12 }

需要应用Context对象时,使用@Inject 标记,Roboguice会自动注入所需Context对象。

定义一个InjectContextDemo,使用一个TextView来显示ContextInfo的getPackageName内容。

1 public class InjectContextDemo extends RoboActivity {
2  
3  @InjectView (R.id.textview) TextView textView;
4  @Inject ContextInfo contextInfo;
5  
6  @Override
7  public void onCreate(Bundle savedInstanceState) {
8  super.onCreate(savedInstanceState);
9  
10  setContentView(R.layout.injectcontext);
11  textView.setText(contextInfo.getPackageName());
12  
13  }
14  
15 }

在InjectContextDemo中定义一个InjectContextDemo,也使用@Inject 通知Roboguice自动创建它的一个实例。Roboguice在创建这个对象时,调用其Injectable 构造函数(参见Android RoboGuice 使用指南(10): Just-in-time Bindings ),自动传入Context对象。

如果需要应用Application对象,可以将构造函数改为

1 @Inject
2  ContextInfo(RoboguiceDemoApplication context){
3  this.context=context;
4 }

或引用Activity

1 @Inject
2  ContextInfo(Activity context){
3   this.context=context;
4 }

本例下载

 

 

Android RoboGuice 使用指南(16):Standard Injection

为方便起见,Roboguice针对Android平台常用的一些对象或服务提供了“标准注入”支持。比如无需使用(SensorManager) getSystemService(SENSOR_SERVICE) 来取得SensorManger 实例,而直接使用@Inject 标记

@Inject SensorManager sensorManager;

Roboguice 自动为sensorManager 注入所需SensorManger 对象, Roboguice支持的标准注入有如下:

@Inject ContentResolver contentResolver;
@Inject AssetManager assetManager;
@Inject Resources resources;
@Inject LocationManager locationManager;
@Inject WindowManager windowManager;
@Inject LayoutInflater layoutInflater;
@Inject ActivityManager activityManager;
@Inject PowerManager powerManager;
@Inject AlarmManager alarmManager;
@Inject NotificationManager notificationManager;
@Inject KeyguardManager keyguardManager;
@Inject SearchManager searchManager;
@Inject Vibrator vibrator;
@Inject ConnectivityManager connectivityManager;
@Inject WifiManager wifiManager;
@Inject InputMethodManager inputMethodManager;
@Inject SensorManager sensorManager;

我们使用SensorManager 为例,说明一下Standard Injection的用法,本例基于Android ApiDemos示例解析(90):OS->Sensors 。

修改

private SensorManager mSensorManager;

private @Inject
SensorManager mSensorManager;

去掉onCreate 中的

mSensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);

运行实例,可以看出不用使用getSystemService,Roboguice自动为mSensorManager 赋了值。

本例下载

 

 

Android RoboGuice 使用指南(17):Inject Extra

使用Intent 启动一个Activity,Service等时,可以通过putExtra 传送数据,被触发的Activity,Service可以使用getIntent()的getExtras 取的Extra的Bundle ,然后再根据Extra的键值(Key)取的对应的参数值。

RoboGuice提供了一个简洁的方法来取得 这些Extra 值,通过@InjectExtra 标记。

本例使用两个Activity,InjectExtraDemo 用来触发InjectExtraReceiver,在InjectExtraDemo中创建Intent时,通过putExtra 放置两个参数Extra1,Extra2.

1 public class InjectExtraDemo extends RoboActivity {
2  
3  @InjectView (R.id.button) Button button;
4  @Inject Context context;
5  
6  
7  @Override
8  public void onCreate(Bundle savedInstanceState) {
9  super.onCreate(savedInstanceState);
10  setContentView(R.layout.injectextra);
11  button.setOnClickListener(mGoListener);
12  }
13  
14  private OnClickListener mGoListener = new OnClickListener()
15  {
16  public void onClick(View v)
17  {
18  Intent di = new Intent();
19  di.setClass(context, InjectExtraReceiver.class) ;
20  di.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK
21  | Intent.FLAG_ACTIVITY_SINGLE_TOP);
22  di.putExtra("Extra1","Message1");
23  di.putExtra("Extra2","Message2");
24  context.startActivity(di);
25  }
26  };
27  
28 }

在InjectExtraReceiver 通过@InjectExtra 标记 ,Roboguice自动为这些变量注入由Intent传入的值,Optional=true表示该Extra为可选,如果传入的Intent不含这个Extra时,值为null.

1 public class InjectExtraReceiver extends RoboActivity{
2  
3  @InjectView (R.id.textview) TextView textView;
4  @InjectExtra ("Extra1" ) String extra1;
5  @InjectExtra ("Extra2" ) String extra2;
6  @InjectExtra (value="Extra3" , optional=true) String extra3;
7  
8  @Override
9  public void onCreate(Bundle savedInstanceState) {
10  super.onCreate(savedInstanceState);
11  
12  setContentView(R.layout.injectextrareceiver);
13  
14  textView.setText("Extra1:"+extra1
15  +"\r\nExtra2:"+extra2
16  +"\r\nExtra3:"+extra3);
17  
18  }
19  
20 }

本例下载

 

Android RoboGuice 使用指南(18):Inject Resources

Roboguice 对访问res 目录下各种资源drawable, arrary, string 等也提供了注入支持。可以通过@InjectResource 很方便的应用所需资源。

本例修改Android ApiDemos示例解析(48):Content->Resources->Resources 使用Inject Resource方法来访问资源。

1 public class InjectResourceDemo extends RoboActivity {
2  
3  @InjectView (R.id.styled_text) TextView styled_text;
4  @InjectView (R.id.plain_text) TextView plain_text;
5  @InjectView (R.id.res1) TextView res1;
6  @Inject Resources res;
7  @InjectResource(R.string.styled_text) String str;
8  
9  
10  @Override
11  public void onCreate(Bundle savedInstanceState) {
12  super.onCreate(savedInstanceState);
13  setContentView(R.layout.injectresource);
14  
15  //Use res to get the string resources
16  CharSequence cs=res.getText(R.string.styled_text);
17  // Note the use of
18  // CharSequence instead of String
19  // so we don't lose the style info.
20  styled_text.setText(cs);
21  
22  // Use the same resource, but convert it to
23  // a string, which causes it
24  // to lose the style information.
25  plain_text.setText(str);
26  res1.setText(cs);
27  
28  }
29  
30 }

本例下载

 

Android RoboGuice 使用指南(19):发送接收Events

Roboguice 提供了对Context 生命周期相关的事件的send 和receive ,系统缺省支持的事件为:

  • OnActivityResultEvent
  • OnConfigurationChangedEvent
  • OnContentChangedEvent
  • OnContentViewAvailableEvent
  • OnCreateEvent
  • OnDestroyEvent
  • OnNewIntentEvent
  • OnPauseEvent
  • OnRestartEvent
  • OnResumeEvent
  • OnStartEvent
  • OnStopEvent

一个简单的例子如下:

1 public class MyActivity extends RoboActivity {
2  // You must "register" your listener in the current
3  // context by injecting it.
4  // Injection is commonly done here in the activity,
5  //but can also be done anywhere really.
6  @Inject protected MyListeners myListeners;
7  
8 }
9  
10  
11 // In this example, all the listeners are in a
12 // MyListeners class, but really they could
13 // be anywhere as long as it's registered.
14 // You can even put the listeners directly into
15 // your activity classes if you like!
16 class MyListeners {
17  
18  // Any method with void return type and a
19  // single parameter with @Observes annotation
20  // can be used as an event listener.
21  //This one listens to onResume.
22  public void doSomethingOnResume(
23  @Observes OnResumeEvent onResume ) {
24  Ln.d("Called doSomethingOnResume in onResume");
25  }
26  
27  // As you might expect, some events can
28  //have parameters.  The OnCreate event
29  // has the savedInstanceState parameter that
30  //Android passes to onCreate(Bundle)
31  public void doSomethingElseOnCreate(
32  @Observes OnCreateEvent onCreate ) {
33  Ln.d("onCreate savedInstanceState is %s",
34  onCreate.getSavedInstanceState())
35  }
36  
37  // And of course, you can have multiple
38  //listeners for a given event.
39  // Note that ordering of listener execution
40  //is indeterminate!
41  public void xxx( @Observes OnCreateEvent onCreate ) {
42  Ln.d("Hello, world!")
43  }
44 }

有关Events的注意事项如下:

  • 在Context中使用@Inject定义事件的Listener.
  • Event只能在某一特定的Context(Activity)中传送,不能跨Context发送,接受。
  • Event除了提供上面列出的Context相关事件外,也可以使用自定义的事件。
  • @observes 只能应用到方法上,而不能应用到构造函数上。

下面使用一个自定义事件MyEvent,通过observer 这个自定义事件来发送,接收自定义事件。

1 public class EventDemo extends RoboActivity {
2  
3  @Inject protected EventManager eventManager;
4  @InjectView (R.id.button) Button button;
5  
6  @Override
7  public void onCreate(Bundle savedInstanceState) {
8  super.onCreate(savedInstanceState);
9  setContentView(R.layout.eventdemo);
10  button.setOnClickListener(mGoListener);
11  }
12  
13  private OnClickListener mGoListener = new OnClickListener()
14  {
15  public void onClick(View v)
16  {
17  eventManager.fire(EventDemo.this,new MyEvent());
18  }
19  };
20  
21  
22  protected void handleEvent(@Observes MyEvent event){
23  Toast.makeText(this"Custom event",
24  Toast.LENGTH_LONG).show();
25  }
26 }
27  
28  
29 class MyEvent{
30  //put any memeber you want here.
31 }

本例下载


1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 、4下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合;、下载 4使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合;、 4下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。
1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 1、资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.m或d论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。 、1资源项目源码均已通过严格测试验证,保证能够正常运行; 2、项目问题、技术讨论,可以给博主私信或留言,博主看到后会第一时间与您进行沟通; 3、本项目比较适合计算机领域相关的毕业设计课题、课程作业等使用,尤其对于人工智能、计算机科学与技术等相关专业,更为适合; 4、下载使用后,可先查看README.md或论文文件(如有),本项目仅用作交流学习参考,请切勿用于商业用途。 5、资源来自互联网采集,如有侵权,私聊博主删除。 6、可私信博主看论文后选择购买源代码。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值