android - 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
)
}
}
我的问题是,
我的方法正确吗?因为我做了所有这些
Activity
而不是RecyclerView.Adapter
.为什么
findViewHolderForAdapterPosition()
即使在我打电话后也总是返回 nullsmoothScrollToPosition()
?
解决方案
为什么即使我调用了 smoothScrollToPosition(),findViewHolderForAdapterPosition() 总是返回 null?
这是因为 smoothScrollToPosition 实际运行动画。因此,您至少必须提供延迟或检查是否smoothScroll
已完成工作。
请参见此处: 检查 smoothScrollToPosition 何时完成
我的方法正确吗?因为我在 Activity 而不是 RecyclerView.Adapter 中完成了所有这些。
我更喜欢你在adapter.onBindViewHolder
在活动中,您可以smoothScrollToPosition
将标志赋予项目。在onBindViewHolder
中,检查标志,如果标志为真,则运行动画,然后重置标志。
推荐阅读
- hiveql - 如何自动化数据质量规则的执行过程?
- php - 延迟运行 Laravel 计划
- javascript - 图像自动更改 - 开始按钮
- reverse-engineering - 呼叫后指令的ESP在哪里?
- python - Kivy Graph 在初始化时闪烁并重复
- python - 当json中有多个嵌套结构时如何将json转换为csv?
- php - 在 win64 客户端上使用 Web 应用程序控制 LPT 硬件
- javascript - 有没有办法从 nashron 获取 javascript 关键字和保留字?
- python - PyGObject 模板子未定义
- java - Java Eclipse 通过 Tomcat 连接到 MySQL