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

AndroidAnnotations 註解全解:告別 findViewById 與匿名監聽器

編輯:關於 Android 程式設計

AndroidAnnotations 是一個以編譯期產生程式碼為核心的開發框架,透過 Java 註解把 findViewById、setOnClickListener、Intent 傳值、執行緒切換等樣板程式碼全部省掉。本文依功能分類整理常用註解。

一、元件宣告類

@EActivity / @EFragment

@EActivity(R.layout.main)
public class MyActivity extends Activity { }

@EFragment(R.layout.my_fragment_layout)
public class MyFragment extends Fragment { }

使用時要記得,框架會在編譯期產生一個「原名 + 下底線」的子類別,因此 XML 中要寫 com.company.MyFragment_,程式碼中則是 new MyFragment_()。

@EBean:把普通類別變成可注入的元件

@EBean
public class MyClass { }

@EActivity
public class MyActivity extends Activity {
    @Bean MyOtherClass myOtherClass;
    @Bean(MyImplementation.class) MyInterface myInterface;   // 也可注入介面
}

限制:這個類別只能有一個建構子,且最多只能有一個 Context 參數。若需要單例,宣告為 @EBean(scope = Scope.Singleton);但單例類別中不可注入 View 或事件綁定,因為它的生命週期比 Activity / Service 更長,容易造成記憶體洩漏。

還可以在注入完成後插入自訂邏輯:

@AfterInject
public void doSomethingAfterInjection() {
    // 此時 notificationManager 等依賴都已就緒
}

@EView / @EViewGroup

@EView
public class CustomButton extends Button {
    @App MyApplication application;
    public CustomButton(Context context, AttributeSet attrs) {
        super(context, attrs);
    }
}
// 使用:CustomButton button = CustomButton_.build(context);
@EViewGroup(R.layout.title_with_subtitle)
public class TitleWithSubtitle extends RelativeLayout {
    @ViewById protected TextView title, subtitle;
    // ...
}

其他元件

@EApplication public class MyApplication extends Application { }
@EService     public class MyService extends Service { }
@EReceiver    public class MyReceiver extends BroadcastReceiver { }
@EProvider    public class MyContentProvider extends ContentProvider { }
// Service 的啟動與停止
MyService_.intent(getApplication()).start();
MyService_.intent(getApplication()).stop();

另外 @Receiver 可以在 Activity 內直接取代宣告整個 BroadcastReceiver:

@EActivity
public class MyActivity extends Activity {
    @Receiver(actions = "org.androidannotations.ACTION_1")
    protected void onAction1() { }
}

二、視圖與資源注入

@EActivity
public class MyActivity extends Activity {
    @ViewById EditText myEditText;              // 變數名需與 id 一致
    @ViewById(R.id.myTextView) TextView textView;

    @StringRes(R.string.hello) String myHelloString;   // 不可宣告為 private
    @ColorRes(R.color.backgroundColor) int someColor;
    @AnimationRes(R.anim.fadein) Animation fadein;
    @DimensionRes(R.dimen.fontsize) float fontSizeDimension;
    @SystemService NotificationManager notificationManager;
    @HtmlRes(R.string.hello_html) Spanned myHelloString2;
}

其他資源註解還包括 @BooleanRes、@ColorStateListRes、@DrawableRes、@IntArrayRes、@IntegerRes、@LayoutRes、@MovieRes、@TextRes、@TextArrayRes、@StringArrayRes 等。

@AfterViews:視圖注入完成後的初始化時機

這一點非常關鍵:初始化 View 的程式碼要寫在 @AfterViews 標註的方法中,不要寫在 onCreate(),因為 onCreate() 執行時 view 尚未注入。

@EActivity(R.layout.main)
public class MyActivity extends Activity {
    @ViewById TextView myTextView;

    @AfterViews
    void updateTextWithDate() {
        myTextView.setText("Date: " + new Date());
    }
}

三、Intent 傳值

@EActivity
public class MyActivity extends Activity {
    @Extra("myStringExtra") String myMessage;
    @Extra String anotherMessage;    // 名稱自動對應變數名
}

// 帶值跳轉
MyActivity_.intent().myMessage("hello").start();

四、事件綁定

@Click(R.id.myButton)
void myButtonWasClicked() { }

@Click                       // 不指定 id 時,方法名即為 id 名稱
void anotherButton() { }

@Click
void yetAnotherButton(View clickedView) { }

其他點擊相關:@LongClick(長按)、@Touch(觸碰)。AdapterView 系列則有 @ItemClick、@ItemLongClick、@ItemSelect,方法參數可以是 position,也可以直接是 Adapter 的實體物件:

@ItemClick
public void myListItemClicked(MyItem clickedItem) { }   // 等同 adapter.getItem(position)

@ItemClick
public void myListItemClicked(int position) { }

文字與進度條監聽

@TextChange(R.id.helloTextView)
void onTextChangesOnHelloTextView(CharSequence text, TextView hello, int before, int start, int count) { }

@BeforeTextChange(R.id.helloTextView)
void beforeTextChangedOnHelloTextView(TextView hello, CharSequence text, int start, int count, int after) { }

@AfterTextChange(R.id.helloTextView)
void afterTextChangedOnHelloTextView(Editable text, TextView hello) { }

@SeekBarProgressChange(R.id.seekBar)
void onProgressChangeOnSeekBar(SeekBar seekBar, int progress, boolean fromUser) { }

此外還有 @SeekBarTouchStart 與 @SeekBarTouchStop 分別對應開始與結束拖曳的事件。

五、選單

@EActivity
@OptionsMenu(R.menu.my_menu)
public class MyActivity extends Activity {

    @OptionMenuItem MenuItem menuSearch;

    @OptionsItem(R.id.menuShare)
    void myMethod() { }

    @OptionsItem
    void homeSelected() { }        // 對應 R.id.home

    @OptionsItem
    boolean menuSearch() {         // 回傳 false 讓系統繼續處理,true 表示已消費
        menuSearch.setVisible(false);
        return true;
    }

    @OptionsItem({ R.id.menu_search, R.id.menu_delete })
    void multipleMenuItems() { }
}

六、執行緒模型

@Background
void someBackgroundWork(String aParam, long anotherParam) { }

@UiThread
void doInUiThread(String aParam, long anotherParam) { }

@Background(delay = 2000)                       // 延遲 2 秒
void doInBackgroundAfterTwoSeconds() { }

@Background(id = "cancellable_task")            // 可取消的任務
void someCancellableBackground() { }

BackgroundExecutor.cancelAll("cancellable_task", true);

還可用 @Background(serial = "test") 讓多個背景方法序列執行,避免並發;@UiThread 則可用 propagation = Propagation.REUSE 在已處於 UI 線程時直接執行、不必再切換。

背景任務回報進度到 UI 的標準寫法:

@EActivity
public class MyActivity extends Activity {
    @Background
    void doSomeStuffInBackground() {
        publishProgress(0);
        publishProgress(100);
    }

    @UiThread
    void publishProgress(int progress) {
        // 更新進度條
    }
}

七、Activity 結果回傳

@OnActivityResult(REQUEST_CODE)
void onResult(int resultCode, Intent data) { }

@OnActivityResult(ANOTHER_REQUEST_CODE)
void onResult(Intent data) { }

小結

AndroidAnnotations 的價值在於把「宣告式」的部分交給註解、把「邏輯」留給自己,程式碼行數與可讀性都大幅改善。官方 Cookbook(github.com/excilys/androidannotations/wiki/Cookbook)有更完整的清單。需要注意的是,本框架主要活躍於 2013~2015 年間,新專案若導入應先評估其與新版 Android Gradle Plugin、AndroidX 的相容性,或考慮改用 Kotlin 的 view binding、Hilt 等現代方案。

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