Android(安卓)自定义注解
16lz
2021-01-25
近来研究了一下android自定义注解,参考ButterKnife,实现一个注解布局
1. 创建一个注解类,activity默认方法是setContentView(),那自定义的注解类就叫BindContentView吧
/** * Created by micki on 2017/11/24. * activity布局id注解 */@Retention(RetentionPolicy.RUNTIME)@Target(ElementType.TYPE)public @interface BindContentView { int value();}
2. 创建好注解类后,要解析处理这个注解类
/** * Created by micki on 2017/11/24. * 注解处理 */public class AnnotationUtils { public static void injectContentView(Activity activity) { Class a = activity.getClass(); if (a.isAnnotationPresent(BindContentView.class)) { // 获取注解类 BindContentView bindContentView = (BindContentView) a.getAnnotation(BindContentView.class); int layoutId = bindContentView.value(); // 得到传入注解类布局id try { Method method = a.getMethod("setContentView", int.class); method.setAccessible(false); method.invoke(activity, layoutId); } catch (NoSuchMethodException e) { e.printStackTrace(); } catch (IllegalAccessException e) { e.printStackTrace(); } catch (InvocationTargetException e) { e.printStackTrace(); } } }}
3. 然后就可以在activity里面使用咯
@BindContentView(R.layout.activity_main) // 传入布局idpublic class MainActivity extends AppCompatActivity { @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); AnnotationUtils.injectContentView(this); // 注册注解类 }}
4. 顺带附上kotlin版本
/** * Created by micki on 2017/11/24. * activity布局id注解 */@kotlin.annotation.Retention(AnnotationRetention.RUNTIME)@Target(AnnotationTarget.CLASS, AnnotationTarget.FILE)annotation class BindContentViewK(val value: Int)
/** * Created by micki on 2017/11/24. * 注解处理 */object AnnotationUtilsK { fun injectContentView(activity: Activity) { val a = activity.javaClass if (a.isAnnotationPresent(BindContentViewK::class.java)) { val contentView = a.getAnnotation(BindContentViewK::class.java) as BindContentViewK val layoutId = contentView.value try { val method = a.getMethod("setContentView", Int::class.javaPrimitiveType) method.isAccessible = false method.invoke(activity, layoutId) } catch (e: NoSuchMethodException) { e.printStackTrace() } catch (e: IllegalAccessException) { e.printStackTrace() } catch (e: InvocationTargetException) { e.printStackTrace() } } }}
是不是超简单呢,按照这个方式,也可以自己定义findViewById,onClick等等,可以打造一个自己的ButterKnife了
更多相关文章
- Android实现自定义view---绘制图片
- 第三节 布局
- 写在20110721:横竖屏切换
- 自定义样式去除标题栏(TItleBar)
- android中Animation的使用!
- java 自定义注解(翻译)
- RadioButton样式自定义
- AlertDialog使用自定义的布局
- Android使用自定义View继承SurfaceView实现动态折线图的绘制