你的位置:首页 > 软件开发 > 操作系统 > 使用Kotlin对ViewGroup的视图进行函数使操作

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

发布时间:2015-12-03 20:00:05
原文标题:Functional operations over Views in ViewGroup using Kotlin原文链接:http://antonioleiva.com/functional-operations-viewgroup-kotlin/原文作者:Anto ...

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

原文标题: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 和继承类提供一个简单的方法做那项工作:

 1 fun ViewGroup.asSequence(): Sequence<View> = object : Sequence<View> { 2  3   override fun iterator(): Iterator<View> = object : Iterator<View> { 4     private var nextValue: View? = null 5     private var done = false 6     private var position: Int = 0 7  8     override public fun hasNext(): Boolean { 9       if (nextValue == null && !done) {10         nextValue = getChildAt(position)11         position++12         if (nextValue == null) done = true13       }14       return nextValue != null15     }16 17     override fun next(): View {18       if (!hasNext()) {19         throw NoSuchElementException()20       }21       val answer = nextValue22       nextValue = null23       return answer!!24     }25   }26 }

原标题:使用Kotlin对ViewGroup的视图进行函数使操作

关键词:ie

ie
*特别声明:以上内容来自于网络收集,著作权属原作者所有,如有侵权,请联系我们: admin#shaoqun.com (#换成@)。