在使用RecyclerView进行开发时,使用notifyItemRemoved()方法删除条目和notifyItemMoved()方法移动条目,遇到删除和移动的条目出现紊乱。
1.删除
本来是删除条目3,没想到结果却是删除了条目4。
在RecyclerView中,并没有提供条目点击监听接口,所以只得在 public void onBindViewHolder(final RecyclerView.ViewHolder holder, final int position)方法中通过holder.itemView.setOnLongClickListener()和holder.itemView.setOnClickListener()来监听条目长按和点击事件,关于点击的条目位置是通过参数position来确定的,查看onBindViewHolder()方法的注释:
/** * Called by RecyclerView to display the data at the specified position. This method * should update the contents of the {@link ViewHolder#itemView} to reflect the item at * the given position. * <p> * Note that unlike {@link android.widget.ListView}, RecyclerView will not call this * method again if the position of the item changes in the data set unless the item itself * is invalidated or the new position cannot be determined. For this reason, you should only * use the <code>position</code> parameter while acquiring the related data item inside this * method and should not keep a copy of it. If you need the position of an item later on * (e.g. in a click listener), use {@link ViewHolder#getPosition()} which will have the * updated position. * * @param holder The ViewHolder which should be updated to represent the contents of the * item at the given position in the data set. * @param position The position of the item within the adapter's data set. */ public abstract void onBindViewHolder(VH holder, int position);从中知道,如果需要监听条目点击的事件,使用ViewHolder的getLayoutPosition()(getPosition()被抛弃)方法才能获得更新后的条目位置,因此:
holder.itemView.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { holder.getPosition();//not position } });传入的条目位置索引应该使用getLayoutPosition()(getPosition()被抛弃)方法来获取,这样就不会出现条目紊乱。
2.置顶
置顶之后,再滑动,条目变回原来的顺序,查看notifyItemMoved()方法的注释:
/** * Notify any registered observers that the item reflected at <code>fromPosition</code> * has been moved to <code>toPosition</code>. * * <p>This is a structural change event. Representations of other existing items in the * data set are still considered up to date and will not be rebound, though their * positions may be altered.</p> * * @param fromPosition Previous position of the item. * @param toPosition New position of the item. */ public final void notifyItemMoved(int fromPosition, int toPosition) { mObservable.notifyItemMoved(fromPosition, toPosition); }
int position = holder.getPosition(); String object = mDatas.get(position); mDatas.remove(position); mDatas.add(0,object); notifyItemMoved(position, 0);