以下的內容僅適用於RoboGuice 2.X

RoboGuice是在android使用google guice最簡單的方式,而且,它還額外提供@InjectView,@InjectResource可以將元件或資料直接注入RoboActivity中.

設定Activity使用RoboActivity

原本的HelloAndroidActivity是繼承Activity,為了讓Activity可以被自動injected,HelloAndroidActivity需改繼承自RoboActivity

    public class HelloAndroidActivity extends RoboActivity {
     
        private static String TAG = "myapp";
     
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.main);
        }
    }

建立view元件(button)
    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        >
    <TextView  
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:text="@string/hello"
        />
    <!-- 新增一個button的view元件,並將id設定為MyButton -->    
    <Button android:id="@+id/MyButton" android:text="Button" android:layout_width="wrap_content" android:layout_height="wrap_content"></Button>
    </LinearLayout>

將view元件(button)注入Activity中
    public class HelloAndroidActivity extends RoboActivity {
     
        @InjectView(R.id.MyButton)
        Button button;
     
        private static String TAG = "myapp";
     
        @Override
        public void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            Log.i(TAG, "onCreate");
            setContentView(R.layout.main);
            button.setText("Injected button");
        }
    }

    @InjectView(R.id.MyButton)
    Button button;

宣告一個button並將常常xml裡的MyButton注入這個button instance.上面的動作,等效於傳統的findViewById() method

    Button button;
    @Override
    public void onCreate(Bundle savedInstanceState) {
     button = (Button) findViewById(R.id.MyButton); 
    }

這樣設定後,執行android application就可以看到MyButton被注入

InjectExtra

public class MyActivity extends RoboActivity {
    @InjectExtra("foo")
    private int myData; // 效果等同於 myData = getIntent.getIntExtra("foo", 0)
 
    @InjectExtra(value="bar", optional=true)
    private String myData2; // optional如果=true,那intent中不見得要含包bar,但如果為false,intent沒有包含bar,則會出exception (預設值為false)
}
}

Resource