RecyclerView findViewHolderForLayoutPosition 和 findViewHolderForAdapterPosition returns 空

RecyclerView findViewHolderForLayoutPosition and findViewHolderForAdapterPosition returns null

我只是想在屏幕上看到我的视图持有者,但方法 findViewHolderFor* 几乎总是被赋予 null 对象。

我的适配器代码:

fun getVisibleViewHolder(recyclerView: RecyclerView) {
    for (i in 0 until recyclerView.childCount) {
        val viewHolder = recyclerView.findViewHolderForLayoutPosition(i) // null: most of the time (specially when scroll performed)
        val viewHolder = recyclerView.findViewHolderForAdapterPosition(i) // idem
    }
}

有时会奏效,但很少见。

所以我找到了解决方案!和解释。 recyclerView.childCount = parent中与位置明显不同的元素个数!

    for (i in 0 until recyclerView.childCount) {
        val view = recyclerView.getChildAt(i)
        val viewHolder = recyclerView.findContainingViewHolder(view)
        ... // the purpose, getting the data from the user here
    }