RecyclerView onclick -滚动到该项目并显示褪色的背景



我最近实现了一个onclick事件来滚动到特定的ViewHolder并触发褪色的背景。

但是,当RecyclerView有很多项目时,所选的ViewHolder没有填充,因此ViewHolder`` that out of theRecyclerView ' ' '没有突出显示,就会出现问题。

// Function to show a faded background for OnClick item
fun fadedBackground(view: View, context: Context) {
val colorFade = ObjectAnimator.ofObject(
view,
"backgroundColor" /*view attribute name*/,
ArgbEvaluator(),
ContextCompat.getColor(context, R.color.list_item_selected_state) /*from color*/,
ContextCompat.getColor(context, R.color.list_item_normal_state) /*to color*/
).apply {
duration = 5000
startDelay = 200
}
colorFade.start()
}
val rvItem = chatRecycler.findViewHolderForAdapterPosition(position)  
if (rvItem != null) {   
// item that not require scrolling
fadedBackground(
rvItem.itemView.message_wrapper,
this@ChatActivity
)
} else {
// item that require scrolling, set background when scrolling stop
// chatRecycler.smoothScrollToPosition(replyInt)

val viewholder = chatRecycler.findViewHolderForAdapterPosition(replyInt)  <-- ALWAYS RETURN NULL

if(viewholder != null) {
fadedBackground(
aa.itemView.message_wrapper,
this@ChatActivity
)
}
}

我的问题是,

  1. 我的方法正确吗?因为我在Activity而不是RecyclerView.Adapter中完成了所有这些。

  2. 为什么findViewHolderForAdapterPosition()总是返回null,即使我调用smoothScrollToPosition()?

为什么findViewHolderForAdapterPosition()总是返回null,即使我调用smoothscrolltopposition ()?

这是因为smoothscrolltopposition实际上运行动画。因此,您必须至少提供延迟或检查smoothScroll是否已完成其工作。

看这里:检查smoothscrolltopposition是否完成

我的方法正确吗?因为这些都是在Activity中完成的而不是在RecyclerView.Adapter中。

我更喜欢你在adapter.onBindViewHolder上运行动画

在活动中,您可以执行smoothScrollToPosition并为项目提供标志。在onBindViewHolder中,您检查标志,如果标志为真,则运行动画,然后重置标志。

你可以像这样给RecyclerView添加一个ScrollListener

chatRecycler.smoothScrollToPosition(position)
chatRecycler.addOnScrollListener(object: RecyclerView.OnScrollListener() {
override fun onScrollStateChanged(recyclerView: RecyclerView, newState : Int) {
when (newState) {
RecyclerView.SCROLL_STATE_IDLE -> {
//When we reached the target position
recyclerView.removeOnScrollListener(this)
//Animate background color when recyclerview stops scrolling
val rvItem = recyclerView.findViewHolderForAdapterPosition(position)
if (rvItem != null) {
fadedBackground(
rvItem.itemView.message_wrapper,
this@ChatActivity
)
}
}
}
}
})

最新更新