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

用注解一次搞定 Android 控件綁定:BindView 自製實作

編輯:關於 Android 程式設計

每次寫 Activity 都要 findViewById 一堆,再一個個轉型賦值,畫面一複雜就顯得囉嗦。既然 Java 5 就有注解與反射,我們完全可以自己造一個類似 ButterKnife 的 @BindView,用一行注解把欄位和 layout 裡的 view 綁起來。

一、定義注解 BindView.java

自訂注解需要兩個關鍵設定:@Target 限定只能標在欄位上,@Retention 設為 RUNTIME 才能在執行期用反射讀取。另外附帶一個 click 屬性,用來決定要不要順便掛上點擊監聽。

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface BindView {
    int id();
    boolean click() default false;
}

二、處理器 AnnotateUtil.java

核心邏輯是:用 getDeclaredFields() 取出目前類別的所有欄位,逐一檢查有沒有 BindView 注解,有的話就依 id 去根 view 底下找對應的 view,setAccessible(true) 後反射寫入;若 click 為 true,順便把自己當成 OnClickListener 綁上去。

public static void initBindView(Object currentClass, View sourceView) {
    Field[] fields = currentClass.getClass().getDeclaredFields();
    if (fields != null && fields.length > 0) {
        for (Field field : fields) {
            BindView bindView = field.getAnnotation(BindView.class);
            if (bindView != null) {
                int viewId = bindView.id();
                boolean clickLis = bindView.click();
                try {
                    field.setAccessible(true);
                    if (clickLis) {
                        sourceView.findViewById(viewId)
                                .setOnClickListener((View.OnClickListener) currentClass);
                    }
                    field.set(currentClass, sourceView.findViewById(viewId));
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

為了讓 Activity、Fragment、甚至單純的 View 都能用,這裡提供了三個重載版本:

public static void initBindView(Activity aty) {
    initBindView(aty, aty.getWindow().getDecorView());
}

public static void initBindView(View view) {
    Context cxt = view.getContext();
    if (cxt instanceof Activity) {
        initBindView((Activity) cxt);
    } else {
        Log.d(TAG, "the view don't have root view");
    }
}

@TargetApi(11)
public static void initBindView(Fragment frag) {
    initBindView(frag, frag.getActivity().getWindow().getDecorView());
}

三、怎麼用

在 Activity 或 Fragment 中,只要標上注解,並在 onCreate 裡呼叫一次工具方法:

@BindView(id = R.id.headerlayout)
private HeaderLayout headerLayout;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_weather);
    AnnotateUtil.initBindView(this);
}

Adapter 的 ViewHolder 也吃這一套

因為方法接受的是「物件 + 根 view」,所以列表項的 ViewHolder 同樣能享受懶人綁定的好處,這也是效能上比較妥當的用法——只呼叫一次,不像 item 每次都重找:

@Override
public View getView(int position, View view, ViewGroup viewGroup) {
    Holder holder;
    if (view == null) {
        view = mInflater.inflate(android.R.layout.simple_list_item_1, null);
        holder = new Holder(view);
        view.setTag(holder);
    } else {
        holder = (Holder) view.getTag();
    }
    County county = (County) getItem(position);
    holder.textView.setText(county.getCountyName());
    return view;
}

private class Holder {
    @BindView(id = android.R.id.text1)
    public TextView textView;

    public Holder(View view) {
        AnnotateUtil.initBindView(this, view);
    }
}

整套機制寫下來不到一百行,卻能讓程式碼乾淨很多。真正上專案時,效能與穩健度都經過反覆打磨的開源方案(如 ButterKnife)仍然是更保險的選擇。

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