免费注册 查看新帖 |

Chinaunix

  平台 论坛 博客 文库
最近访问板块 发新帖
查看: 1113 | 回复: 0
打印 上一主题 下一主题

使用注解简化findViewById [复制链接]

论坛徽章:
0
跳转到指定楼层
1 [收藏(0)] [报告]
发表于 2015-07-13 10:49 |只看该作者 |倒序浏览
在android开发activity时需要通过findViewById取得布局中的view元素,但如果元素太多时需要重复调用该方法,从而导致代码臃肿。可以通过注解来精简代码。

主要注解类与annot processo
  1. @Retention(RetentionPolicy.RUNTIME)
  2. @Target(ElementType.FIELD)
  3. public @interface ViewField {
  4.     /**
  5.      * view对应的id
  6.      *
  7.      * @return
  8.      */
  9.     int value();

  10.     public static class Processor {
  11.         public static void process(Activity activity) throws Exception {
  12.             Field[] fields = activity.getClass().getDeclaredFields();
  13.             ViewField annot = null;
  14.             for (Field field : fields) {
  15.                 annot = field.getAnnotation(ViewField.class);
  16.                 if (annot != null) {
  17.                     field.setAccessible(true);
  18.                     field.set(activity, activity.findViewById(annot.value()));
  19.                 }
  20.             }
  21.         }
  22.     }
  23. }
复制代码
Activity中调用示例
  1. @ViewField(R.id.btn_ok)
  2. Button btnOK;
  3. @ViewField(R.id.et_orig)
  4. EditText etOrig;
  5. @ViewField(R.id.et_dest)
  6. EditText etDest;

  7. @Override
  8. public void onCreate(Bundle savedInstanceState) {
  9.     super.onCreate(savedInstanceState);
  10.     setContentView(R.layout.new_task_layout);

  11.     try {
  12.         ViewField.Processor.process(this);
  13.     } catch (Exception e) {
  14.         throw new RuntimeException("加载view错误", e);
  15.     }
  16. }
复制代码
您需要登录后才可以回帖 登录 | 注册

本版积分规则 发表回复

  

北京盛拓优讯信息技术有限公司. 版权所有 京ICP备16024965号-6 北京市公安局海淀分局网监中心备案编号:11010802020122 niuxiaotong@pcpop.com 17352615567
未成年举报专区
中国互联网协会会员  联系我们:huangweiwei@itpub.net
感谢所有关心和支持过ChinaUnix的朋友们 转载本站内容请注明原作者名及出处

清除 Cookies - ChinaUnix - Archiver - WAP - TOP