天天看點

Android依賴注入:Google Guice on Android的使用及相關資源

本文轉自:http://blog.csdn.net/sangming/article/details/8878104

RoboGuice 使用谷歌自己的Guice庫,給Android帶來了簡單和易用的依賴注入。如果你使用過Spring或Guice的話,你可能已經知道這種程式設計方式是多麼的便捷。

RoboGuice 允許使用annotation 的方式來描述id于View之間的關系,其餘的工作由roboGuice庫來完成。比如:

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 );  

 }  

}  

如果使用roboguice 來寫:

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;  

隻需使用@InjectView 來描述 view 和Id之間的關系,RoboGuice 自動完成餘下的工作,代碼簡潔易讀。

注意:activity必須繼承自RoboActivity

繼續閱讀