首页 > 解决方案 > RecyclerView onclick - 滚动到该项目并显示褪色背景

问题描述

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

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

// 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()

标签: androidandroid-recyclerview

解决方案


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

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

请参见此处: 检查 smoothScrollToPosition 何时完成

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

我更喜欢你在adapter.onBindViewHolder

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


推荐阅读