使用Kotlin对ViewGroup的视图进行函数使操作

时间:2025-04-06 09:06:08

原文标题:Functional operations over Views in ViewGroup using Kotlin

原文链接:http://antonioleiva.com/functional-operations-viewgroup-kotlin/

原文作者:Antonio Leiva(http://antonioleiva.com/about/

原文发布:2015-07-29

使用Kotlin对ViewGroup的视图进行函数使操作

集合、迭代、数组、序列 ... 所有这些共用一套好用的函数,这组函数可帮助对它们的元素进行转换、排序以及其它操作。但是,由于类的构造方法,在Android SDK中,有部分函数还不能用。

例如,我们不能直接获得ViewGroup内部视图列表,所以这些操作是不可能使用的。但是并非所有一切都失去了。在Kotlin中,我们有方法为这些操作准备任何数据。诀窍简单:我们只需要创建一个Sequence。在我们的例子中,Sequence将是一组有序的View。我们只需要实现一个函数,其返回Iterator

如果我们有了Sequence,函数式操作领域就为我们打开了使用它们的大门。所以让我们从它开始。

注:阅读文章结尾

如lakedaemon666在评论中所建议的那样,有一个不用Sequence的更简单的方法可以获得同样的结果。我会保留原文记录,但是建议你看看替代的解决方案。

创建ViewGroup的Sequence

如前所述,我们将创建迭代器(iterator),它必须知道是否有下一项,下一项是哪个。我们还创建一个扩展函数,为了任何 ViewGroup 和继承类提供一个简单的方法做那项工作:

 fun ViewGroup.asSequence(): Sequence<View> = object : Sequence<View> {

     override fun iterator(): Iterator<View> = object : Iterator<View> {
private var nextValue: View? = null
private var done = false
private var position: Int = 0 override public fun hasNext(): Boolean {
if (nextValue == null && !done) {
nextValue = getChildAt(position)
position++
if (nextValue == null) done = true
}
return nextValue != null
} override fun next(): View {
if (!hasNext()) {
throw NoSuchElementException()
}
val answer = nextValue
nextValue = null
return answer!!
}
}
}

检索视图递归列表

获得一个视图列表,并对其进行函数操作是非常有用的。因此,我们可以先创建顶层视图列表,然后,用它以递归方式逐级检索ViewGroup中视图。

让我们为ViewGroup创建新扩展属性。扩展属性非常类似扩展函数,可用于任何类:

 public val ViewGroup.views: List<View>
get() = asSequence().toList()

我们可以用这,创建递归函数,它返回布局中任何ViewGroup内部的所有View

 public val ViewGroup.viewsRecursive: List<View>
get() = views flatMap {
when (it) {
is ViewGroup -> it.viewsRecursive
else -> listOf(it)
}
}

flatMap,我们把全部结果的多个列表转换到一个列表中。它将遍历任何视图;如果是ViewGroup,它还会遍历自己的视图。否则,就返回仅有一项的列表。

用法实例

现在,我们得到viewRecursive属性,执行我们想要的任何操作。这里你可以看到两个例子。我创建这样一个简单的布局:

使用Kotlin对ViewGroup的视图进行函数使操作

 <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
tools:context=".MainActivity"> <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"/> <FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"> <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Hello Java"/> <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="Hello Kotlin"/> <TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="end"
android:text="Hello Scala"/> </FrameLayout> <LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:orientation="horizontal"> <CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Check 1"/> <CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Check 2"/> <CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Check 3"/> <CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Check 4"/> </LinearLayout> </RelativeLayout>

例如,在MainActivity.onCreate()中,可应用这段代码。它将Hello Kotlin!串转换为大写字母,选中偶数复选框:

 val container: ViewGroup = find(R.id.container)
val views = container.viewsRecursive // Set Kotlin TextView to Upper
val kotlinText = views.first {
it is TextView && it.text.toString().contains("Kotlin")
} as TextView
kotlinText.text = kotlinText.text.toString().toUpperCase() // Set even checkboxes as checked, and odd as unchecked
views filter {
it is CheckBox
} forEach {
with(it as CheckBox) {
val number = text.toString().removePrefix("Check ").toInt()
setChecked(number % 2 == 0)
}
}

使用Kotlin对ViewGroup的视图进行函数使操作

替代的解决方案

如lakedaemon666在评论中所提及的那样(谢谢解释),如果之后我们遍历整个sequence,那么创建sequence就没有什么意义了。例如,当按行读取文件时,sequence是懒惰迭代。只有要求必要的项目。而我们却要使用所有项,所以简单的列表就足够了。

另外,有许多简单的方法可以产生视图列表。我们可以依赖值域产生视图的索引列表,将它们映射到我们需要的视图列表中。所有这一切就一行:

 public val ViewGroup.views: List<View>
get() = (0..getChildCount() - 1) map { getChildAt(it) }

总结

这是个无聊的例子,但是这个概念或许可使你的所有代码函数化,停止依靠那些典型迭代式编程的循环和其它控制流。

记住从我写的书《Android开发者的Kotlin》中,你能够学习到Kotlin的这点以及许多其它能力,你将通过从0开始创建Android APP学习Kotlin。