Reference: https://github.com/roboguice/roboguice/wiki
最經接觸到一些java的注入知識,找了下相關資料github上有個RoboGuice的庫,挺不錯的,還有一系列的說明文檔,拿來翻譯傳播一下。
RoboGuice是一個旨在簡化Android開發和消除類依賴的注入框架,使用了Google的Guice庫。如果你曾今使用過Spring框架(基於java語言的企業級開發框架,現在已經比J2EE本身更為流行)或者Guice,那么你就會知道這種編程是多么方便。
為了是你有一個大致概念,先來看一個簡單的例子,這是一個典型的Android activity:
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(),那將不得的不看上5行意義不大的初始化代碼,然后才會看待真正有價值的代碼:name.setText().如果activities更加復雜那么像這樣的初始化代碼就會更多。
現在比較一下同樣的一個程序,這次我們將使用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; public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); name.setText( "Hello, " + myName ); } }
在這個例子中,onCreate()一看就簡單多了。所有平台相關的初始化操作都沒有了,我們看到的僅僅是程序的邏輯代碼。如果你需要一個系統服務呢?注入一個。如果你需要一個View或者Resource?也注入吧,RoboGuice會處理這些細節。
RoboGuice的目的在於是你的代碼真正的和你的程序相關,而不是去維護一堆初始化或生命周期的代碼。
關於如何配置RoboGuice來運行你的程序,請參考安裝的相關篇幅。