本文介绍的是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)
}