[英]How to find out item is created in recycler view for the first time?
I have a recycler view and I want to find out if an item is created in recycler view for the first time or not?我有一个回收站视图,我想知道一个项目是否是第一次在回收站视图中创建的?
Is there an event handler for it?有它的事件处理程序吗?
Note: I know how to implement it with flag, but I'm looking for another approach.注意:我知道如何使用标志来实现它,但我正在寻找另一种方法。
Why do you want this?你为什么要这个? To my mind it seems like there is not a good reason to know this information, a ViewHolder should be independent from that knowledge.在我看来,似乎没有充分的理由知道这些信息,ViewHolder 应该独立于这些知识。
Nothing is provided for this by RecyclerView.Adapter , the only callbacks are to manage the ViewHolder instances, which can be recycled and so any particular instance wouldn't know if it is the first instance or not. RecyclerView.Adapter没有为此提供任何内容,唯一的回调是管理ViewHolder实例,该实例可以回收,因此任何特定实例都不知道它是否是第一个实例。
You could store a flag in your data model and access it when you set up the ViewHolder in onBindViewHolder
, as you seem to know.正如您似乎知道的onBindViewHolder
,您可以在数据模型中存储一个标志,并在您在 onBindViewHolder 中设置 ViewHolder 时访问它。
You can ovveride onViewAttachedToWindow(holder: ViewHolder) in your recycler adapter.您可以在回收器适配器中覆盖 onViewAttachedToWindow(holder: ViewHolder)。 sample code like this:示例代码如下:
private var isFirstChildAttached = false // single fire
override fun onViewAttachedToWindow(holder: ViewHolder) {
super.onViewAttachedToWindow(holder)
holder.pageView.registerTopLevelTouchListener()
if (!isFirstChildAttached) {
isFirstChildAttached = true
checkAndFirePageDimen(holder.itemView)
}
}
private fun checkAndFirePageDimen(itemView: View){
itemView.viewTreeObserver.addOnGlobalLayoutListener(object : ViewTreeObserver.OnGlobalLayoutListener {
override fun onGlobalLayout() {
itemView.viewTreeObserver.removeOnGlobalLayoutListener(this)
pagerCallback.onFirstItemAttachedToPager(itemView)
}
})
}
"checkAndFirePageDimen" helps you for reliable itemView size. “checkAndFirePageDimen”帮助您获得可靠的 itemView 大小。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.