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

androidannotations 使用入門:跟 findViewById 說再見

編輯:關於 Android 程式設計

AndroidAnnotations 是一個相當成熟的框架(專案 Wiki),它把幾件麻煩事一起包辦了:

  • 依賴注入(Dependency Injection)
  • 簡化的執行緒模型(Simplified threading model)
  • 事件綁定(Event binding)
  • REST Client

好用之外,更關鍵的一點是:它對執行效能沒有影響。原因後面會講。

一、從一個最小例子開始

AndroidManifest.xml

注意這裡宣告的 Activity 名稱,後面都多帶了一個下劃線。


<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="com.example.hello"
    android:versionCode="1"
    android:versionName="1.0">

    <uses-sdk android:minSdkVersion="14" android:targetSdkVersion="18" />

    <application android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name">

        <activity android:name="com.example.hello.MainActivity_"
            android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>

        <activity android:name="com.example.hello.SecondActivity_" />
    </application>
</manifest>

MainActivity.java

這裡的類名反而不帶下劃線,帶下劃線的是編譯期自動產生的子類。

@EActivity(R.layout.activity_main)
public class MainActivity extends Activity {

    @ViewById(R.id.myInput)
    EditText myInput;

    @ViewById(R.id.myTextView)
    TextView textView;

    @ViewById(R.id.myButton2)
    Button btn2;

    @StringRes(R.string.go_to_second)
    String btn2Txt;

    @AfterViews
    protected void afterViews() {
        btn2.setText(btn2Txt);
    }

    @Click
    void myButton() {
        String name = myInput.getText().toString();
        textView.setText("Hello " + name);
    }

    @Click
    void myButton2() {
        SecondActivity_.intent(this).start();
    }
}

activity_main.xml

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <EditText android:id="@+id/myInput"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <Button android:id="@+id/myButton"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Click me!" />

    <TextView android:id="@+id/myTextView"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" />

    <Button android:id="@+id/myButton2"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/go_to_second" />
</LinearLayout>

註解一上,代碼立刻清爽了,那一大堆 findViewById 不見了。SecondActivity 的源碼這裡就不貼了。

二、如何編譯運行

  • 使用 javac:需要傳入 -AandroidManifestFile=/path/to/AndroidManifest.xml 參數,明確指出清單檔位置。
  • 使用 Eclipse:專案上按右鍵 → Properties → Java Compiler → Annotation Processing,勾選 Enable annotation processing;接著在 Factory Path 中加入 AndroidAnnotations 的 jar。
  • 使用 Maven:maven-compiler-plugin 3.1 起支援設定編譯參數。
<plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.1</version>
    <configuration>
        <encoding>UTF-8</encoding>
        <source>1.6</source>
        <target>1.6</target>
        <compilerArgs>
            <arg>-Atrace=true</arg>
            <arg>-AlogLevel=trace</arg>
            <arg>-AlogConsoleAppender=true</arg>
            <arg>-AandroidManifestFile=/path/to/AndroidManifest.xml</arg>
        </compilerArgs>
    </configuration>
</plugin>

常用編譯參數

  • trace(boolean):啟用或停用 @Trace 註解,該註解會透過 log 記錄方法執行。
  • androidManifestFile(String):預設會在父目錄中遞尋 AndroidManifest.xml,工程結構特殊時可用它明確指定。
  • resourcePackageName(String):R 類別不在預設 package 時,用它指定。
  • logFile(String):3.0 起使用自訂 logger,預設寫入 {outputFolder}/androidannotations.log。{outputFolder} 依序尋找 target → build → bin → 專案根目錄;找不到時可用 logFile 指定輸出路徑,並支援佔位符動態命名。
  • logLevel(trace/debug/info/warn/error):預設 DEBUG,排查問題時改成 TRACE 更有用。
  • logAppenderConsole(boolean):預設啟用 FileAppender 與 MessagerAppender,設為 true 會多開一個 ConsoleAppender。
  • threadControl(boolean):控制 @SupposeUiThread 與 @SupposeBackground,預設 true,可確保方法在正確的執行緒被呼叫。

三、對效能的影響:幾乎為零

因為它的原理是在編譯期產生 Activity 的子類,而不是執行期反射。看看編譯器幫我們自動生出的類別就很清楚:

public final class MainActivity_ extends MainActivity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        init_(savedInstanceState);   // 處理 @StringRes、@ColorRes 等
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);   // 對應 @EActivity
    }

    private void init_(Bundle savedInstanceState) {
        Resources resources_ = this.getResources();
        btn2Txt = resources_.getString(R.string.go_to_second);
    }

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);
        afterSetContentView_();
    }

    private void afterSetContentView_() {
        // @ViewById
        textView = (TextView) findViewById(R.id.myTextView);
        myInput = (EditText) findViewById(R.id.myInput);
        btn2 = (Button) findViewById(R.id.myButton2);

        // @Click
        View view = findViewById(R.id.myButton2);
        if (view != null) {
            view.setOnClickListener(new OnClickListener() {
                @Override
                public void onClick(View v) {
                    MainActivity_.this.myButton2();
                }
            });
        }
        afterViews();   // 呼叫 @AfterViews 標註的方法
    }

    public static IntentBuilder_ intent(Context context) {
        return new IntentBuilder_(context);
    }

    public static class IntentBuilder_ {
        private final Context context_;
        private final Intent intent_;

        IntentBuilder_(Context context) {
            context_ = context;
            intent_ = new Intent(context, MainActivity_.class);
        }

        public IntentBuilder_ flags(int flags) {
            intent_.setFlags(flags);
            return this;
        }

        public void start() {
            context_.startActivity(intent_);
        }

        public void startForResult(int requestCode) {
            if (context_ instanceof Activity) {
                ((Activity) context_).startActivityForResult(intent_, requestCode);
            } else {
                context_.startActivity(intent_);
            }
        }
    }
}

所有注入與事件綁定都變成了普通的 findViewById 與 setOnClickListener,跟手寫的沒兩樣,自然沒有額外的效能負擔。

四、完整的 pom.xml 範例

<project xmlns="https://maven.apache.org/POM/4.0.0"
    xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">
    <modelVersion>4.0.0</modelVersion>
    <groupId>org.androidannotations</groupId>
    <artifactId>maveneclipse</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <packaging>apk</packaging>

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <android.version>4.1.1.4</android.version>
        <androidannotations.version>3.2</androidannotations.version>
        <java.version>1.6</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>com.google.android</groupId>
            <artifactId>android</artifactId>
            <version>${android.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.androidannotations</groupId>
            <artifactId>androidannotations</artifactId>
            <version>${androidannotations.version}</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>org.androidannotations</groupId>
            <artifactId>androidannotations-api</artifactId>
            <version>${androidannotations.version}</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.1</version>
                <configuration>
                    <source>${java.version}</source>
                    <target>${java.version}</target>
                    <compilerArgs>
                        <arg>-AlogLevel=trace</arg>
                    </compilerArgs>
                </configuration>
            </plugin>
            <plugin>
                <groupId>com.jayway.maven.plugins.android.generation2</groupId>
                <artifactId>android-maven-plugin</artifactId>
                <version>3.9.0-rc.3</version>
                <configuration>
                    <sdk><platform>${android.platform}</platform></sdk>
                    <undeployBeforeDeploy>true</undeployBeforeDeploy>
                </configuration>
                <extensions>true</extensions>
            </plugin>
        </plugins>
    </build>
</project>

小提醒:這套寫法屬於 APT 時代的方案,在今日的專案中通常會改用 DataBinding、ViewBinding 或 Hilt 等更現代的工具;但理解「編譯期生成代碼」這個思路,對讀懂那些框架仍然很有幫助。

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