如何解放findViewById

注解,对,就是它
下面来详细介绍
首先,我们要新建一个注解类,类似于Override这个类,我们称作InterpretView

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

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

然后我们建一个类似于操作类的类,这个类通过反射来执行findViewById方法,我们称作Interpretor

import java.lang.annotation.Annotation;
import java.lang.reflect.Field;

import android.app.Activity;

public final class Interpretor {
    private final Activity mActivity;
    //构造方法
    private Interpretor(Activity activity) {
        mActivity = activity;
    }
    //获取Interpretor实例
    public static Interpretor get(Activity activity) {
        return new Interpretor(activity);
    }
    //这个方法最重要
    public void interpret() {
        //遍历
        for (Field field : mActivity.getClass().getDeclaredFields()) {
            //获取注解
            for (Annotation annotation : field.getAnnotations()) {
                //当注解为InterpretView时候,执行相应的动作
                //在这个地方执行findViewById方法,然后将值赋给相应的变量
                if (annotation.annotationType().equals(InterpretView.class)) {
                    try {
                        Class<?> fieldType = field.getType();
                        int idValue = InterpretView.class.cast(annotation).value();
                        field.setAccessible(true);
                        Object injectedValue = fieldType.cast(mActivity
                                .findViewById(idValue));
                        if (injectedValue == null) {
                            throw new IllegalStateException("findViewById("
                                    + idValue + ") gave null for " + field
                                    + ", can't inject");
                        }
                        field.set(mActivity, injectedValue);
                        field.setAccessible(false);
                    } catch (IllegalAccessException e) {
                        throw new IllegalStateException(e);
                    }
                }
            }
        }
    }
}

好了,两个类都完成了,那么我们怎么使用呢??
原始的方法:

private TextView text01 = null;

text01 = (TextView)findViewById(R.id.text01);

现在的方法:

@InterpretView(R.id.text01)
private TextView text01 = null;

ok,完成。。。

哦,对了,使用注解的时候,要**在OnCreate方法中setContentView()后面执行
Interpretor.get(this).interpret();**
否则不会给text01赋值的哦

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值