无法映射视图组子级

时间:2018-10-30 17:31:19

标签: android kotlin

为什么地图在此视图组的孩子列表中不起作用?

class DivisorItem(context: Context): RecyclerView.ItemDecoration() {
private val mDivisor: Drawable? = ContextCompat.getDrawable(context, R.drawable.item_divisor)

override fun onDrawOver(c: Canvas, parent: RecyclerView, state: RecyclerView.State) {
    val left = parent.paddingLeft
    val right = parent.width - parent.paddingRight

    parent.children.map {
        val params = it.layoutParams as RecyclerView.LayoutParams
        val top = it.bottom + params.bottomMargin
        val bottom = top + mDivisor!!.intrinsicHeight
        mDivisor.setBounds(left, top, right, bottom)
        mDivisor.setColorFilter(Color.GRAY, PorterDuff.Mode.SRC_IN)
        mDivisor.draw(c)
    }

}
}

此视图组中有4个视图,但从未在地图块中输入

1 个答案:

答案 0 :(得分:0)

我找到了解决方案... parent.children是序列

我打开了源并找到了它:

val ViewGroup.children: Sequence<View>
get() = object : Sequence<View> {
    override fun iterator() = this@children.iterator()
}

我认为这是不变的……在此代码之上,与我发现的相同来源

operator fun ViewGroup.iterator() = object : MutableIterator<View> {
private var index = 0
override fun hasNext() = index < childCount
override fun next() = getChildAt(index++) ?: throw IndexOutOfBoundsException()
override fun remove() = removeViewAt(--index)

}

所以我将代码更改为:

parent.iterator().forEach {
        val params = it.layoutParams as RecyclerView.LayoutParams
        val top = it.bottom + params.bottomMargin
        val bottom = top + mDivisor!!.intrinsicHeight
        mDivisor.setBounds(left, top, right, bottom)
        mDivisor.setColorFilter(Color.GRAY, PorterDuff.Mode.SRC_IN)
        mDivisor.draw(c)
    }