自己学着写一个BindView来减少findViewById的应用

一、先解释一下注解
大家看到下面代码知道BindView是我们自己写的注解,但是他还有注解,而这样的注解我们叫做元注解,所谓元注解解释负责注解其他注解的注解,哈哈,是不是感觉有点绕口,但是事实就是这样的。
下面就讲一下java5.0定义的元注解:
1.@Target
2.@Retention
3.@Documented
4.Inherited

@Target:
@Target说明了Annotation所修饰的范围:Annotation可被用于Packages、Types(类、接口、枚举、Annotation类型)、类型成员(方法、构造方法、成员变量、枚举值)、方法参数和本地变量(如循环变量、catch参数)。

@Retention:
表示需要在什么级别保存该注释信息,用于描述注解的生命周期(即:被描述的注解在什么范围内有效)

@Inherited:
  @Inherited 元注解是一个标记注解,@Inherited阐述了某个被标注的类型是被继承的。如果一个使用了@Inherited修饰的annotation类型被用于一个class,则这个annotation将被用于该class的子类。
  
@Documented:
  @Documented用于描述其它类型的annotation应该被作为被标注的程序成员的公共API,因此可以被例如javadoc此类的工具文档化。Documented是一个标记注解,没有成员。

大概讲解了一下注解,就可以更加清晰的认识一下我们自己写的BindView了。
二、下面就是上代码了:

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

public class AnnotationUtils{
    public static void injectView(Object obj,View rootView){
        Field[] fields = obj.getClass().getDeclareDFields();
        if(fields!=null&&fields.length>0){
            for(int i=0;i<fields.length;i++){
                Field field = fields[i];
                BindView bindView = field.getAnnotation(BindView.class);
                if(bindView!=null){
                    int id = bindView.id();
                    boolean click = bindView.click();
                    field.setAccessible(true);
                    try{
                      if(click){
                       rootView.findViewById(id).setOnClickListener((View.OnClickListener)obj);
                      } 
                      field.set(obj,rootView.findView(id)); 
                    }catch(Exception e){

                    }
                }
            }
        }
    }

    public static injectView(Activity activity){
        injectView(activity,activity.getWindow().getDecorView());
    }

    @TargetApi(11)
    public static injectView(Fragment fragment){
        injectView(framgent,fragment.getActivity().getWindow().getDecorView);
    }
}


//下面就是BindView的应用
public class MainActivity extends Activity{

    @BindView(id=R.id.text)
    private TextView text;

    protected void onCreate(Bundle savedInstanceState){
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        AnnotationUtils.injectView(this);
    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值