AndroidAnnotation配置與使用
背景
隨著安卓手機在市場上的普及,安卓開發的需求也越來越大。但是在安卓開發過程中,其實很多操作都是較為繁瑣,且沒有必要的,雖然一天下來看看寫的代碼很多,但是可能也就一個介面,幾個功能點。所以對於安卓開發中代碼的簡化和重用是十分有必要的。
昨天偶然在網易雲課堂上看到了AndroidAnnotation這個第三方架構,據說能夠大幅度簡化安卓編程,提高編程效率。懷著一顆好東西都要嘗試一下的心態,今天將之配置並嘗試了一下。
配置
AndroidAnnotation的官網為http://androidannotations.org/。但是事實上,在這個網站上只有一個例子代碼展示它能夠如何如何簡化代碼,實際的內容主要還是在github上。
通過串連開啟git,進入它的git wiki。在這裡可以下載jar包,並由一些如何使用的guide。包括如何在Eclipse和IntelliJ上配置。不過在這裡它講的比較簡單,如果按照它的方法配置,可能會遇到很多問題。另外bz用的時AndroidStudio,雖然是基於IntelliJ,但是不知為何在細節上還是有些差距的,比如AndroidStudio上就沒有Annotation Processing這個設定項。所以我們需要找尋一種適用於AndroidStudio且更為簡潔的方式。
得益於Gradle,我們可以直接使用build檔案引入AndroidAnnotation。這裡需要五步。
1.引入對android-apt的依賴。在app module的build檔案中添加以下代碼。
buildscript { repositories { mavenCentral() } dependencies { classpath 'com.neenbedankt.gradle.plugins:android-apt:1.2+' }}apply plugin: 'android-apt' //添加android-apt外掛程式
2.設定android-apt參數 。注意把包名換成你的應用的。另外outputs[0]是在新的android-studio的版本中才需要加的。
apt { arguments { androidManifestFile variant.outputs[0].processResources.manifestFile resourcePackageName 你的包名 }}
3.使用apt引入對androidannotation的依賴。
dependencies { apt org.androidannotations:androidannotations:3.0+ compile org.androidannotations:androidannotations-api:3.0+ compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:21.0.3'}
5.最後的build檔案應該是這樣的。
buildscript { repositories { mavenCentral() } dependencies { classpath 'com.neenbedankt.gradle.plugins:android-apt:1.2+' }}apply plugin: 'com.android.application'apply plugin: 'android-apt'android { compileSdkVersion 21 buildToolsVersion 21.1.2 defaultConfig { applicationId com.tanglikang.annotationtest minSdkVersion 9 targetSdkVersion 21 versionCode 1 versionName 1.0 } buildTypes { release { minifyEnabled false proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro' } }}apt { arguments { androidManifestFile variant.outputs[0].processResources.manifestFile resourcePackageName com.tanglikang.annotationtest }}dependencies { apt org.androidannotations:androidannotations:3.0+ // add these compile org.androidannotations:androidannotations-api:3.0+ // two lines compile fileTree(dir: 'libs', include: ['*.jar']) compile 'com.android.support:appcompat-v7:21.0.3'}
6.重新build工程,系統會自動下載依賴的第三方庫。然後就可以使用AndroidAnnotation了。
使用
AndroidAnnotation的使用其實很簡單,主要需要注意兩個點。
一是標籤的使用。AA中有很多有用的標籤,具體可以參考以下網頁:https://github.com/excilys/androidannotations/wiki/AvailableAnnotations。
二是在編譯工程的時候,AA會將原來的Activity換成Activity_的形式,所以需要在AndroidMainfest中也做相應地修改。
這裡嘗試一個最簡單地例子。這裡使用了三個標籤@EActivity設定布局檔案。@ViewById引入一個控制項。@Click設定空間點擊事件。
@EActivity(R.layout.activity_main)public class MainActivity extends ActionBarActivity { @ViewById(R.id.tv_1) TextView hello; @Click(R.id.tv_1) public void showToast(){ Toast.makeText(MainActivity.this, ok, Toast.LENGTH_LONG).show(); } @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); }}
總結
經過實踐,AndroidAnnotation確實能夠大幅度增加android編程效率,值得學習和使用。