Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

AndroidAnnotations 框架入門與 Android Studio 配置詳解

編輯:關於 Android 程式設計

最近手邊的事情比較多,也有好一陣子沒更新部落格了。這兩天研究了名為 AndroidAnnotations 的開源框架,實際用起來相當順手,寫法讓人聯想到 Spring 的註解風格——概念上很容易理解,真正的門檻在於環境配置那一段。

關於框架本身的介紹網上已經汗牛充棟,這裡就不再重複。先整理幾個關鍵連結:

1、官方網站:https://androidannotations.org/(可能需要特殊網路環境)

2、Eclipse 下的配置說明:https://github.com/excilys/androidannotations/wiki/Eclipse-Project-Configuration

3、Android Studio 下的配置(本文重點)。

一、在 Android Studio 中搭建 AndroidAnnotations 環境

建立 module 之後,你會發現有兩個 build.gradle 檔案:一個位於 app 模組內(僅對該 module 生效),另一個位於整個專案根目錄(全域生效)。這個工具的 application 目錄下可以容納多個 module(相當於 Eclipse 中的多個 project)。

配置大致分為兩步。

局部 build.gradle(app 模組)

apply plugin: 'com.android.application'
apply plugin: 'android-apt'
def AAVersion = '3.0.1'

android {
    compileSdkVersion 19
    buildToolsVersion "20.0.0"

    defaultConfig {
        applicationId "com.tongbu.mytest"
        minSdkVersion 8
        targetSdkVersion 19
        versionCode 1
        versionName "1.0"
    }
    buildTypes {
        release {
            runProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:19.+'

    apt "org.androidannotations:androidannotations:$AAVersion"
    compile "org.androidannotations:androidannotations-api:$AAVersion"
}

apt {
    arguments {
        androidManifestFile variant.processResources.manifestFile
        resourcePackageName 'com.tongbu.mytest'
    }
}

全域 build.gradle(專案根目錄)

buildscript {
    repositories {
        jcenter()
    }
    dependencies {
        classpath 'com.android.tools.build:gradle:0.12.+'
        classpath 'com.neenbedankt.gradle.plugins:android-apt:1.3'
    }
}

allprojects {
    repositories {
        jcenter()
    }
}

以上都完成後,你已經接近尾聲。接著還要把 AndroidManifest.xml 中每個 Activity 的名稱後面加上底線「_」。原因是這個框架在編譯解析時,會把 MainActivity 對應成 MainActivity_.class,因此清單檔裡必須補上底線,否則會報錯。

不過事情通常不會這麼順利。補上底線後,你會發現 IDE 提示找不到 MainActivity_ 這個類別。別擔心,它是在編譯過程中動態產生的,只要點一下編譯按鈕讓它生成即可。

做到這裡,Android Studio 上的 AndroidAnnotations 環境就配置完成了。Eclipse 的資料比較多,這裡暫不展開。

二、常用註解示範

@NoTitle          // 無標題列
@Fullscreen       // 全螢幕
@EActivity(R.layout.activity_my)
public class MyActivity extends ActionBarActivity {

    // ============ 基本注入註解 ============
    @ViewById Button button1;
    @ViewById Button button2;
    @ViewById(R.id.textview1) TextView textView;   // 指定 id 注入
    @ViewById ProgressBar progressBar;
    @ViewById ImageView imageView;

    // 取得系統 service,取代原本手動 getSystemService 的寫法
    @SystemService ClipboardManager clipboardManager;

    @Click({R.id.button1, R.id.button2, R.id.button3, R.id.button4})
    public void simpleButtonOnClicked(View view) {
        switch (view.getId()) {
            case R.id.button1: textView.setText("Button1 is Clicked!"); break;
            case R.id.button2: textView.setText("Button2 is Clicked!"); break;
            case R.id.button3:
                String content = clipboardManager.getText().toString();
                Toast.makeText(getApplicationContext(), "剪貼簿內容: " + content, Toast.LENGTH_SHORT).show();
                break;
            case R.id.button4:
                Toast.makeText(getApplicationContext(), "進度條啟動!", Toast.LENGTH_SHORT).show();
                progressBarWorks();
                break;
        }
    }

    @LongClick({R.id.button2})
    public void buttonOnLongClicked(View view) {
        switch (view.getId()) {
            case R.id.button1: textView.setText("Button1 is LongClicked!"); break; // 未註冊,不會觸發
            case R.id.button2: textView.setText("Button2 is LongClicked!"); break; // 可觸發
        }
    }

    // ============ 資源相關註解 ============
    @AnimationRes(R.anim.rotate) Animation animationRotate;
    @DrawableRes(R.drawable.myphoto) Drawable myphoto;
    @ColorRes(R.color.love) Integer mycolor;
    @TextRes(R.string.textres) CharSequence text;

    @Click({R.id.button5, R.id.button6, R.id.button7})
    public void animationButtonOnClicked(View view) {
        switch (view.getId()) {
            case R.id.button5: imageView.startAnimation(animationRotate); break;
            case R.id.button6: imageView.setImageDrawable(myphoto); break;
            case R.id.button7:
                Toast.makeText(getApplicationContext(), text.toString(), Toast.LENGTH_SHORT).show();
                break;
        }
    }

    // ============ 執行緒相關註解 ============
    // 相當於開啟一個 AsyncTask 或新 Thread
    @Background
    public void progressBarWorks() {
        int i = 1;
        while (i <= 10) {
            Log.e("progress", "進度: " + i);
            try {
                Thread.sleep(1000);
                updateProgressBar(i); // 也可直接 progressBar.setProgress(i)
                i++;
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }

    // 指定在 UI 執行緒執行
    @UiThread
    public void updateProgressBar(int i) {
        progressBar.setProgress(i);
        if (i == 10) {
            Toast.makeText(getApplicationContext(), "進度條結束", Toast.LENGTH_SHORT).show();
        }
    }

    // ============ 生命週期與執行順序 ============
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        Log.e("FirstToLast", "onCreate");
        // setContentView(R.layout.activity_my); 可省略
        // 此時 @ViewById 尚未注入,控制項皆為 null,直接操作會有空指標異常
    }

    @AfterViews
    public void init() {
        Log.e("FirstToLast", "init");
        progressBar.setMax(10); // 需要初始化控制項時,請放在這裡
    }

    @Override protected void onStart()  { super.onStart();  Log.e("FirstToLast", "onStart"); }
    @Override protected void onResume() { super.onResume(); Log.e("FirstToLast", "onResume"); }
}

關鍵提醒:在 onCreate() 被呼叫時,@ViewById 還沒有完成注入,所有控制項都是 null。因此若你要對元件做初始化設定,請改用 @AfterViews 標註的方法。

各方法的實際呼叫順序如下圖:

資源相關的註解還有很多,這裡不逐一列舉:

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved