使用Kotlin Android(安卓)Extensions
16lz
2021-01-26
本文介绍的是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.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) }
更多相关文章
- Android(安卓)contentResolver 进行query 条件为where in时出错
- Android核心程序之SystemUI - (一)开篇
- Android(安卓)MVP模式 谷歌官方代码解读
- 第一个android 程序的学习心得
- Android(安卓)代码中设置EditText只输入数字、字母
- android parcelable 以及android studio插件
- xe5 android 调用照相机获取拍的照片
- 类似Lazy Android的插件,根据layout的xml文件自动生成findViewByI
- Android仿微信UI布局视图(圆角布局的实现)