Android中用注解和反射实现控件的绑定
2015-11-27 14:11
435 查看
<span> </span>在日常的Android开发中,经常出现的findViewById()通常让小伙伴们写的很烦躁,一连串重复的代码严重的影响我们的生产力。现在,让我们用一段代码来简化这些烦躁的没有意义的重复吧,废话不多说,直接上代码:
/** * 注解findviewById * * @param ctx */ public static void inject(Activity ctx) { Class<? extends Activity> class1 = ctx.getClass(); Field[] fields = class1.getDeclaredFields(); for (Field field : fields) { field.setAccessible(true); MyAnnation annotation = field.getAnnotation(MyAnnation.class); if (annotation != null) { try { field.set(ctx, ctx.findViewById(annotation.id())); } catch (Exception e) { e.printStackTrace(); } } } }
@MyAnnation(id = R.id.seekBar1) private SeekBar sb1; @MyAnnation(id = R.id.seekBar2) private SeekBar sb2; @MyAnnation(id = R.id.seekBar3) private SeekBar sb3;
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); AnnotationUtil.inject(this); }注解类:
@Target(ElementType.FIELD) @Retention(RetentionPolicy.RUNTIME) public @interface MyAnnation { public int id(); }
相关文章推荐
- android 设置viewpager滑动速度
- Android Gallery
- Android lint删除无用资源文件
- Android编码时的一些实用小技巧
- Android登录实例——计时显示“隐视密码*”
- Android问题集锦之一:adb devices 出现unauthorized错误
- android应用性能测试之CPU和内存占用
- Android toolbar添加SearchView混淆打包成功后访问出错
- Android Studio修改常用快捷键
- AndroidManifest.xml文件配置整理集合
- Android RecyclerView的使用
- Android二维码讲解(ZXing)
- 深入理解Android(4)——理解Android中的JNI(下)
- Android--Dialog详细讲解
- Android 4.2 禁止下拉状态栏
- 【Android】SlidingMenu属性详解
- Android总结篇系列:Android广播机制
- 深入理解Android(2)——理解Android中的JNI(中)
- Android Paint
- Android平台Camera实时滤镜实现方法探讨(四)--以Hefe滤镜为例