H.K*_*Kim 1 android android-recyclerview
上面的代码是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)
}
}
Run Code Online (Sandbox Code Playgroud)
在这种状态下,我想使用移动功能将值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)
}
}
Run Code Online (Sandbox Code Playgroud)
还有其他解决方法吗?
使用各种notifyItemFoo()方法(如移动/插入/删除)不会重新绑定视图。这是设计使然。你可以打电话
if (from == 0 || to == 0) {
notifyItemChanged(from, Boolean.FALSE);
notifyItemChanged(to, Boolean.FALSE);
}
Run Code Online (Sandbox Code Playgroud)
为了重新绑定移动的视图。
| 归档时间: |
|
| 查看次数: |
524 次 |
| 最近记录: |