Android开发绑定控件注解类
2021-01-12 本文已影响0人
你的益达233
应用技术:注解
注解的作用就不说了,用过Retrofit都知道,它有很多@POST("xxx") @FormUrlEncoded。这就是注解的应用
一、定义注解接口
@Target(AnnotationTarget.FIELD)
@Retention(AnnotationRetention.RUNTIME) //注解保留到程序运行时以及会被加载进入到JVM中,所以在程序运行时可以获取到它们
annotation class BindView(val id:Int,val clickable :Boolean = false) {
}
二、获取到注解后要实现的功能
这里需要用到反射技术
object AnnotationHelper {
/**
* @desc : 绑定控件
* @author : congge on 2019/12/10 11:37
**/
fun initBindView(viewClass: Any, view : View){
//获取所有变量
val fields = viewClass.javaClass.declaredFields
for (field in fields){
//如果变量是在BindView注解上
if (field.isAnnotationPresent(BindView::class.java)){
val bindView = field.getAnnotation(BindView::class.java)
try {
//findView
val findView :View? = view.findViewById(bindView.id)
if (findView != null){
//改写为可见属性
field.isAccessible = true
//向viewClass对象的这个field属性设置新值value
field.set(viewClass,findView)
//设置点击事件
if (bindView.clickable) {
findView.setOnClickListener(viewClass as View.OnClickListener)
}
}
}catch (e:Exception){
e.printStackTrace()
}
}
}
}
}
三、应用场景示例
@BindView(id = R.id.more_value, clickable = true)
private var more_value:TextView? = null
@BindView(id = R.id.tv_cn_like_title)
private var tv_cn_like_title:TextView? = null
override fun initUI() {
header = layoutInflater.inflate(R.layout.fragment_home_header, null)
AnnotationHelper.initBindView(this, header!!)
}
四、总结
通过注解的方式将每一个控件声明时都填上注解,然后再解析阶段通过反射获取所有变量,判断该变量是否有我设定的注解,如果有就获取注解的内容,再通过findViewById就可以获取该id的控件,再通过field.set(viewClass,findView)就可以把控件复制给变量