android通过注解实现findViewById 和 setOnClickListener

来源:互联网 发布:美国eia数据 编辑:程序博客网 时间:2024/04/29 05:06

不多说,上代码

使用
@MyView(value = R.id.text)
TextView t;

@MyClick(value = {R.id.button})
public void myClick(View v){
t.setText(“”+i++);
}

在onCreate()中
MyZhujie.register(this);

ondestroy()
MyZhujie.unRegister(this);

unRegister 需要在super.onDestroy()前

注解1

@Target(ElementType.FIELD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyView {
int value() default 0;
}

注解2

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface MyClick {
int[] value() default 0;
}

初始化工具

class MyZhujie{

static ArrayMap<View,Method> clickIDS = new ArrayMap();static View.OnClickListener mOnclickListener = new View.OnClickListener() {    @Override    public void onClick(View v) {        Method method = clickIDS.get(v);        if(method != null){            try{                method.invoke(v.getContext(),v);            }catch (Exception e){                e.printStackTrace();            }        }    }};public static void register(Activity activity) {    autoInjectAllField(activity);}public static void unRegister(Activity ctx){    try {        zhujie(ctx,false);    } catch (Exception e) {        e.printStackTrace();    }}private static void autoInjectAllField(Activity ctx) {    try {        zhujie(ctx, true);    } catch (Exception e) {        e.printStackTrace();    }}private static void zhujie(Activity ctx , boolean isSet) throws IllegalAccessException {    Class clazz = ctx.getClass();    if(isSet){        Field[] fields = clazz.getDeclaredFields();        for (Field field : fields) {            if (field.isAnnotationPresent(MyView.class)) {                MyView myView = field.getAnnotation(MyView.class);                int id = myView.value();                if (id > 0) {                    field.setAccessible(true);                    field.set(ctx, ctx.findViewById(id));                }            }        }    }    Method[] methods = clazz.getDeclaredMethods();    for(Method mMethod : methods) {        if (mMethod.isAnnotationPresent(MyClick.class)) {            MyClick click = mMethod.getAnnotation(MyClick.class);            int[] ids = click.value();            for (int id : ids) {                View v = ctx.findViewById(id);                if (v != null) {                    if (isSet) {                        v.setOnClickListener(mOnclickListener);                        clickIDS.put(v, mMethod);                    } else {                        v.setOnClickListener(null);                        clickIDS.remove(v);                    }                }            }        }    }}

}

一套简单的注解就完成了

源码
http://download.csdn.net/detail/wwwbjj1988/9604927

0 0
原创粉丝点击