android 绑定控件 麻烦,Android开发绑定控件注解类

应用技术:注解

注解的作用就不说了,用过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)就可以把控件复制给变量

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值