注解式绑定控件

/**
 * 注解式绑定控件-类
 */
@Target(ElementType.FIELD) // 表示类成员
@Retention(RetentionPolicy.RUNTIME) // 表示运行时可获取类成员
public @interface BindView {
    public int id();
}
/**
 * 注解式绑定控件-方法
 * para1 当前的类,为Activity或Fragment
 */
public static void initBindView(Object currentClass) {
    // 通过反射机制获取到类的全部属性
    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();
                try {
                    field.setAccessible(true);
                    // 将currentClass类中的field赋值为sourceView.findViewById(viewId)
                    field.set(currentClass, ((Activity) currentClass).findViewById(viewId));
                }
                catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}

使用方法:

/**
 * 注解式绑定控件声明
 */
@BindView(id = R.id.listview)
private ListView listview;

@BindView(id = R.id.swiperefreshlayout)
private RefreshLayout swipeRefreshLayout;

在onCreate方法中调用:

initBindView(this);

注解式绑定使得代码变得更加简洁,但是反射机制让效率变低。

参考文章地址:
http://mobile.51cto.com/aprogram-449682.htm
http://blog.csdn.net/rain_butterfly/article/details/37931031
http://www.itnose.net/detail/6117657.html
http://www.tuicool.com/articles/f2Y7Rzf

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值