RecyclerView适配器notifyDataSetChanged停止花哨的动画 [英] RecyclerView Adapter notifyDataSetChanged stops fancy animation
问题描述
我建立基于RecyclerView一个组件,允许用户重新排列通过拖放项目。 当我在DragListener身边,我需要它的位置在适配器,以便进行正确的举动,但我只能访问视图。 所以,这里是我做什么,在适配器视图绑定:
I am building a component based on RecyclerView, allowing user to reorder items by drag and drop. Once I am on the DragListener side, I need the position it has in the adapter in order to perform correct move, but I only have access to the view. So here is what I am doing in the adapter view binding :
@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {
Track track = mArray.get(position);
viewHolder.itemView.setTag(R.string.TAG_ITEM_POSITION, position);
}
它看起来正确的吗? 因为如果我移动的项目是这样的:
Does it seem correct to you ? Because if I move an item like this :
public void move(int from, int to){
Track track = mArray.remove(from);
mArray.add(to, track);
notifyItemMoved(from, to);
}
然后位置标记是不正确的了,如果我notifyDataSetChanged(),我失去了花哨的动画。 任何建议?
then position tag is not correct anymore, and if I notifyDataSetChanged(), I lose the fancy animation. Any suggestion ?
推荐答案
没有,那是错的。首先,您不可以引用传递给onBindViewHolder该方法返回后的位置。 RecyclerView不会重新绑定时,它的位置发生变化(由于项目活动等)的景色。
No, it is wrong. First of all, you cannot reference to the position passed to the onBindViewHolder after that method returns. RecyclerView will not rebind a view when its position changes (due to items moving etc).
相反,你可以使用 ViewHolder#为getPosition()
将返回你的更新的位置。
Instead, you can use ViewHolder#getPosition()
which will return you the updated position.
如果你解决这个问题,你的举动code应该和放大器;提供了很好的动画。
If you fix that, your move code should work & provide nice animations.
调用 notifyDataSetChanged
将prevent predictive动画,所以要避免它,只要你能。请参阅<一href="https://developer.android.com/reference/android/support/v7/widget/RecyclerView.Adapter.html#notifyDataSetChanged()"相对=nofollow>有关详细信息,文档。
Calling notifyDataSetChanged
will prevent predictive animations so avoid it as long as you can. See documentation for details.
编辑(从评论):获取位置,从外面,从recyclerview获得子视图持有人,然后得到的VH位置。见RecyclerView API的细节
Edit (from comment): to get position from the outside, get child view holder from recyclerview and then get position from the vh. See RecyclerView api for details
这篇关于RecyclerView适配器notifyDataSetChanged停止花哨的动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!