使用Kotlin Android Extensions

本文介绍的是Kotlin团队开发的一个插件Kotlin Android Extensions,这插件可以让我们用更少的代码来开发程序,目前包括了视图绑定的功能,该插件自动创建了很多的属性来让我们直接访问XML中的view,省去了开发者findViewById。

列举一段常用Android中常用的代码:

val titleView: TextView by bindView(R.id.post_title_text_View)  
val titleText = ......  
if (titleText == null || titleText.isBlank()) {  
        visibility = View.GONE  
} else {  
        titleView.text = titleText  
        visibility = View.VISIBLE  
}  

上面是很常用的对一个title这样的TextView进行setText和设置Visibility。在一个app中,上面代码类似的平时需要用到非常多。这要怎么简化,用extensions可以解决这个问题。

fun TextView.setTextAndVisibility(text: CharSequence?) {  
    if (text.isNullOrBlank()) {  
        visibility = View.GONE  
    } else {  
        this.text = text  
        visibility = View.VISIBLE  
    }  
}  

这样下一次用到就可以直接用:

val titleView: TextView by bindView(R.id.post_title_text_View)  
val titleText = ......  
titleView.setTextAndVisibility(titleText)  

有时,我们在TextView visible的情况下,还需要进行一部分操作;或者我们不一定是TextView,其他View我们也需要进行这样的操作,那么我们可以更写一个更generic的extension。

inline fun <T : View> T.checkTextAndSetVisibility(text: CharSequence?, setter: T.(text: CharSequence) -> Unit) {  
if (text == null || text.isBlank()) {  
visibility = View.GONE  
    } else {  
        setter(text)  
visibility = View.VISIBLE  
    }  
}  

在看看下面这个怎么用:

val topicSectionLink = item.topicSectionLink  
if (topicSectionLink?.title.isNullOrBlank()) {  
            topicTagView.visibility = View.GONE  
} else {  
            topicTagView.visibility = View.VISIBLE  
            topicSectionLink?.let {   
                topicTagView.setTopic(section, item, it)   
            }  
}  

if (subtitle.isNullOrBlank()) {  
            excerptView.visibility = View.GONE  
} else {  
            excerptView.visibility = View.VISIBLE  
            excerptView.setText(subtitle, language)  
}  

简化后:

topicTagView.checkTextAndSetVisibility(topicSectionLink?.title) {  
    topicSectionLink?.let { setTopic(section, item, it) }  
}  
excerptView.checkTextAndSetVisibility(subtitle) {  
    setText(it, language)  
}  
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值