Android使用注解避免大量的findViewById()
16lz
2021-01-24
BindView注解类@Target(ElementType.FIELD)//表示要注解的是一个字段@Retention(RetentionPolicy.RUNTIME)//添加@interface表明这是一个注解,等价于继承了java.lang.annotation.Annotation这个类public @interface BindView { public int id();//view的id 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"); }
更多相关文章
- android sqlite查询数据表的字段与相关属性
- android通过自定义toast实现悬浮通知效果的示例代码
- android fragment用get/setArguments()传值
- Android(安卓)Kotlin入门-属性和字段
- Android(安卓)Gson 操作
- Android短信操作(通过内容提供者)
- Android与JS互相调用以及注意
- Android(安卓)Afianl框架(2)——FinalDB
- Android(安卓)自定义控件,模仿小米秒表样式的时钟,完整代码注解