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

自動化綁定控件:自定義 BindView 註解與反射工具類

編輯:關於 Android 開發

Android 註解式綁定控件 BindView

每次寫 findViewById 都是一種消耗。既然 Java 從 5 就提供了註解與反射,我們完全可以自己造一個輕量版的 @BindView,告別重複勞動。整個方案只需要兩個類。

一、定義註解:BindView.java

用 @Target(ElementType.FIELD) 限定它只能標在字段上,@Retention(RetentionPolicy.RUNTIME) 保證運行時可讀;另外留一個 click 開關,順手把點擊監聽也綁定掉。

package com.practice.noyet.coolweather.util;

import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

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

二、解析工具:AnnotateUtil.java

核心邏輯是遍歷當前對象的所有字段,找出帶 @BindView 的,然後用反射塞值。這裡有幾個實務細節值得注意:

  • field.setAccessible(true):不然無法寫入 private 字段。
  • 重載了三個入口,分別服務 Activity、Fragment 和普通 View,讓調用方式統一。
  • 對普通 View 的處理會檢查它的 Context 是不是 Activity,不是就無法拿到 decorView。
package com.practice.noyet.coolweather.util;

import android.annotation.TargetApi;
import android.app.Activity;
import android.app.Fragment;
import android.content.Context;
import android.util.Log;
import android.view.View;

import java.lang.reflect.Field;

public class AnnotateUtil {

    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();
                    }
                }
            }
        }
    }

    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("AnnotateUtil.java", "the view don't have root view");
        }
    }

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

三、使用方式

在 Activity 或 Fragment 中,只需一行註解加一行初始化:

@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 中,把 sourceView 傳進去即可,這正是它比 findViewById 更清爽的地方——ViewHolder 場景下不再需要為每個控件寫一遍轉型:

package com.practice.noyet.coolweather.adapter;

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import com.practice.noyet.coolweather.model.County;
import com.practice.noyet.coolweather.util.AnnotateUtil;
import com.practice.noyet.coolweather.util.BindView;

public class SpinnerArrayAdapter extends BaseAdapter<County> {

    private LayoutInflater mInflater;

    public SpinnerArrayAdapter(Context context) {
        mInflater = LayoutInflater.from(context);
    }

    @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);
        }
    }
}

要提醒的是,反射本身有性能成本,因此這個方案不適合放在 getView 這種高頻調用路徑上反覆執行。示例中之所以沒問題,是因為解析只在 ViewHolder 首次創建時進行,後續都走 view.getTag() 複用。正式專案若追求極致性能,ButterKnife 這類基於編譯期注解處理的方案會更合適;但如果你只是想理解原理、或需要在無法引入第三方庫的環境裡自己搞定,這份五十行的實現已經足夠。

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