標籤:android開發 開源架構
寫程式的目的當然是為了給使用者提供產品及服務,寫程式是辛苦的,有時要加班加點,要抓破頭皮等。在寫程式的過程中,我們應該盡量讓開發工作變得更輕鬆,更有味。我們能做的每一件事就是盡量減少代碼量,不要重複造輪子。Android開源架構androidannotations(我簡稱AA架構)的目的正是於此,當然代碼量減少了,不僅僅可以讓工作更輕鬆,讓讀代碼的人更輕鬆,維護代碼更爽。正在開發的項目中,我們是用到了androidannotations註解架構,所以簡單地講講:
androidannotations的官方網址:http://androidannotations.org/及github網址:https://github.com/excilys/androidannotations/wiki,兩網址詳細介紹了架構的優勢及使用,架構的搭建工作可以參考:http://blog.csdn.net/limb99/article/details/9067827。下面用兩個簡單的Activity(用的同一個布局檔案,就簡單的6個控制項)來對比下代碼量:
-------------無註解架構的寫法-----------------
public class TestActivity extends Activity {
private TextView textView01;
private TextView textView02;
private TextView textView03;
private TextView textView04;
private TextView textView05;
private Button button;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
this.textView01 = (TextView) findViewById(R.id.textView01);
this.textView02 = (TextView) findViewById(R.id.textView02);
this.textView03 = (TextView) findViewById(R.id.textView03);
this.textView04 = (TextView) findViewById(R.id.textView04);
this.textView05 = (TextView) findViewById(R.id.textView05);
this.button = (Button) findViewById(R.id.button);
this.button.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// 實現點擊事件
}
});
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
setViewData();
}
private void setViewData() {
this.textView01.setText("無AA架構測試1");
this.textView02.setText("無AA架構測試2");
this.textView03.setText("無AA架構測試3");
this.textView04.setText("無AA架構測試4");
this.textView05.setText("無AA架構測試5");
}
}
---------用了androidannotations註解架構寫法----------------------
@EActivity(R.layout.activity_main)
public class AATestActivity extends Activity {
@ViewById(R.id.textView01)
TextView textView01;
@ViewById(R.id.textView02)
TextView textView02;
@ViewById(R.id.textView03)
TextView textView03;
@ViewById(R.id.textView04)
TextView textView04;
@ViewById(R.id.textView05)
TextView textView05;
@ViewById(R.id.button)
Button button;
@Click(R.id.button)
void btnClick() {
// 實現點擊事件
}
@Override
protected void onResume() {
// TODO Auto-generated method stub
super.onResume();
setViewData();
}
private void setViewData() {
this.textView01.setText("無AA架構測試1");
this.textView02.setText("無AA架構測試2");
this.textView03.setText("無AA架構測試3");
this.textView04.setText("無AA架構測試4");
this.textView05.setText("無AA架構測試5");
}
}
相比之下,用了註解寫法,就不用重複寫findViewById()及寫onclick()事件等。這兩個類的代碼量看不去區別不明顯,主要控制項少,而且實現功能少,當我們布局頁面很複雜,要實現很多監聽時,用註解方法的優勢就很明顯。註解方法很多,可以參考http://doc.okbase.net/rain_butterfly/archive/95335.html,使用極為方便,而且經過簡單測試,註解架構對程式的效能影響非常小。
不過在使用的時候,個人發現了幾個感覺不太好的地方:
1,我們寫在Activity中的控制項如Button,不能寫成私人的private Button btn。
2,另外在AndroidManifest.xml資訊清單檔中要把對應的Acitivity(如AATestActivity )寫成AATestActivity _才可以。
3,偵錯工具可能有些不方便。
Android註解架構androidannotations簡介