Android 視圖綁定實現代碼優化

當我們在寫Android代碼的時候有時候UI界面上的控件太多代碼就特別冗餘,findViewById() setOnClickListener()... 鬱悶

看看我一般是怎麼做的吧~

BindView

@Target(ElementType.FIELD)//表示用在字段上
@Retention(RetentionPolicy.RUNTIME)//表示生命週期爲運行時
public @interface BindView {
    public int id();

    public boolean click() default false;
}

AnnotateUtil

public class AnnotateUtil {
    /**
     * @param currentClass
     *            當前類,一般爲Activity或Fragment
     * @param sourceView
     *            待綁定控件的直接或間接父控件
     */
    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 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(
                                    (OnClickListener) currentClass);
                        }
                        // 將currentClass的field賦值爲sourceView.findViewById(viewId)
                        field.set(currentClass, sourceView.findViewById(viewId));
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    /**
     * 必須在setContentView之後調用
     * 
     * @param aty
     */
    public static void initBindView(Activity aty) {
        initBindView(aty, aty.getWindow().getDecorView());
    }

    /**
     * 必須在setContentView之後調用
     * 
     * @param view
     *            侵入式的view,例如使用inflater載入的view
     */
    public static void initBindView(View view) {
        Context cxt = view.getContext();
        if (cxt instanceof Activity) {
            initBindView((Activity) cxt);
        } else {
            throw new RuntimeException("view must into Activity");
        }
    }

    /**
     * 必須在setContentView之後調用
     * 
     * @param frag
     */
    public static void initBindView(Fragment frag) {
        initBindView(frag, frag.getActivity().getWindow().getDecorView());
    }
}

哈哈 是不是很簡單,想怎麼用就怎麼用
發佈了31 篇原創文章 · 獲贊 4 · 訪問量 3萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章