Android代碼注入架構RoboGuice
概述
RoboGuice 2可以讓我們更友善、快捷地編寫android代碼。在寫android代碼時,我們在使用getIntent().getExtras()可能會忘記判空,findViewById()必須強制轉換成TextView很别扭?RobotGuice 2可以幫我們省掉這些步驟。
RoboGuice 2可以注入到View,Resource,System Service或者其他任何對象中,我們不必在關心這些細節。
使用RoboGuice 2可以精簡我們的代碼,這樣會減少bug數量,也使程式更加易讀。在編碼中,我們可以把精力更多地放在業務邏輯上。
使用方法
RobotGuice使用google自己的Guice,讓安卓支援依賴注入,類似于Spring。
傳統的android代碼如下:
class AndroidWay extends Activity {
TextView name;
ImageView thumbnail;
LocationManager loc;
Drawable icon;
String myName;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
name = (TextView) findViewById(R.id.name);
thumbnail = (ImageView) findViewById(R.id.thumbnail);
loc = (LocationManager) getSystemService(Activity.LOCATION_SERVICE);
icon = getResources().getDrawable(R.drawable.icon);
myName = getString(R.string.app_name);
name.setText( "Hello, " + myName );
}
}
上面的代碼共19行。如果我們想閱讀onCreate()方法,得略過上面的變量初始化區域,其實onCreate方法就一樣代碼name.setText(),代碼看起來很臃腫。
下面是使用RoboGuice的代碼:
@ContentView(R.layout.main)
class RoboWay extends RoboActivity {
@InjectView(R.id.name) TextView name;
@InjectView(R.id.thumbnail) ImageView thumbnail;
@InjectResource(R.drawable.icon) Drawable icon;
@InjectResource(R.string.app_name) String myName;
@Inject LocationManager loc;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
name.setText( "Hello, " + myName );
}
}
這個例子中,onCreate()方法就簡潔多了,所有初始化代碼都被移除,隻剩下我們的業務邏輯代碼。需要SystemServce?注入即可。需要View或者Resource?注入即可,RoboGuice會幫我們實作那些細節。
RoboGuice的目标是讓我們的代碼真正關乎于app,而不是維護着一堆堆的初始化、生命周期控制代碼等。