Android Recyclerview中notifyitemmoved()后OnBindViewHolder不适用

2024-01-28

上面的代码是RecyclerViewAdapter,只有当它是第一项时才改变颜色,如下所示。

class TestAdapter : RecyclerView.Adapter<RecyclerView.ViewHolder>() {

private val textColor1 = Color.BLACK
private val textColor2 = Color.YELLOW
private val items = ArrayList<String>()

override fun onBindViewHolder(holder: RecyclerView.ViewHolder, position: Int) {
    val textColor = if(position==0) textColor1 else textColor2
    holder.itemView.textView.setTextColor(textColor)
    holder.itemView.textView.text = items[position]
}

fun move(from:Int,to:Int){
    val item = items[from]
    items.remove(item)
    items.add(to,item)
    notifyItemMoved(from,to)
}
}

在这种状态下,我想使用 move 函数将 Value 3 移动到第一个位置。我想要的结果如下所示。

但事实上,它显示了以下结果

使用notifyDataSetChanged时,看不到动画过渡效果,

使用 findViewHolderForAdapterPosition 手动运行 onBindViewHolder 会产生我想要的结果,但它非常不稳定。 (导致其他部分的错误我没有修复)

fun move(from:Int,to:Int){
    val item = items[from]
    val originTopHolder = recyclerView.findViewHolderForAdapterPosition(0)
    val afterTopHolder = recyclerView.findViewHolderForAdapterPosition(from)
    items.remove(item)
    items.add(to,item)
    notifyItemMoved(from,to)
    if(to==0){
        onBindViewHolder(originTopHolder,1)
        onBindViewHolder(afterTopHolder,0)
    }
}

还有其他方法可以解决这个问题吗?


使用各种notifyItemFoo()方法,如移动/插入/删除,不会重新绑定视图。这是设计使然。你可以打电话

if (from == 0 || to == 0) {
    notifyItemChanged(from, Boolean.FALSE);
    notifyItemChanged(to, Boolean.FALSE);
}

为了重新绑定移动的视图。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Android Recyclerview中notifyitemmoved()后OnBindViewHolder不适用 的相关文章

随机推荐