Android使用注解避免大量的findViewById()

1 篇文章 0 订阅
1 篇文章 0 订阅
BindView注解类
@Target(ElementType.FIELD)//表示要注解的是一个字段
@Retention(RetentionPolicy.RUNTIME)

//添加@interface表明这是一个注解,等价于继承了java.lang.annotation.Annotation这个类
public @interface BindView {
    public int id();//viewid

    public boolean clickable() default false;//是否可点击,默认为false
}

使用
public class AnnotationActivity extends Activity implements View.OnClickListener {

    @BindView(id = R.id.text_anno, clickable = true)
    private TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_annotation);

        initView(this, findViewById(android.R.id.content));
    }

    private void initView(Object viewClass, View view) {
        Field[] fields = viewClass.getClass().getDeclaredFields();
        if (fields != null && fields.length > 0) {
            for (Field field : fields) {
                BindView bindView = field.getAnnotation(BindView.class);
                if (bindView != null) {
                    int id = bindView.id();
                    boolean clickable = bindView.clickable();
                    try {
                        field.setAccessible(true);
                        if (clickable) {
                            view.findViewById(id).setOnClickListener((View.OnClickListener) viewClass);
                        }
                        //viewClass中的field赋值为view.findViewById(id)
                        field.set(viewClass, view.findViewById(id));
                    } catch (IllegalAccessException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }

    @Override
    public void onClick(View v) {
        Toast.makeText(this, "click!", Toast.LENGTH_SHORT).show();
        textView.setText("click");
    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值