> Android在线手册 > 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:

public class InjectViewDemo extends RoboActivity {

 @InjectView (R.id.button) Button goButton;
 @InjectView (R.id.textview1) TextView textView1;
 @InjectView (R.id.textview2) TextView textView2;
 @InjectView (R.id.textview3) TextView textView3;
 @InjectView (R.id.textview4) TextView textView4;

 @Override
 public void onCreate(Bundle savedInstanceState) {
 super.onCreate(savedInstanceState);

 setContentView(R.layout.injectview);
 goButton.setOnClickListener(mGoListener);
 }

 private OnClickListener mGoListener = new OnClickListener()
 {
 public void onClick(View v)
 {
 textView1.setText("Clicked");
 textView2.setText("Clicked");
 textView3.setText("Clicked");
 textView4.setText("Clicked");
 }
 };
}

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

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