Facing issue in Position value during Drag and drop in RecyclerView android

耗尽温柔 提交于 2019-12-04 17:51:22

Make sure you override getItemId() method that returns unique value on your adapter.

When using drag&drop with recyclerView, the positions get mixed up. Then, whenever you do something where you pass the position (such as an animation for example), the wrong item gets the desired action.

To get the actual current position of the item, add a method in your adapter:

private int getItemPosition(Item item){ // (<-- replace with your item)
    int i = 0;
    // (replace with your items and methods here)
    for (Item currentItem : mItems) {
        if (currentItem.getItemId() == item.getItemId()) break;
        i++;
    }
    return i;
}

and then call this instead to get the position.

I had this exact same issue. The problem is that after dragging, "position" passed to onBindViewHolder will change, but onBindViewHolder is never called again so we can't depend on it inside the onClick method. In onBindViewHolder, instead of:

intent.putExtra("NAME_POSITION", position);

use this:

@Override
public void onBindViewHolder(final ItemViewHolder holder, final int position) {

    final Object listItem = list.get(position);

    holder.textView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent intent = new Intent(activity, DetailActivity.class);
            intent.putExtra("NAME_POSITION", list.indexOf(item);
            intent.putParcelableArrayListExtra("NAME_LIST", mName);
            ((Activity) context).startActivityForResult(intent, 800);
        }
 }

Side note, but you'll also want to change your Collections.swap code. It will mess up the order if you quickly drag over multiple spots. Use this instead:

if (fromPosition < toPosition) {
    for (int i = fromPosition; i < toPosition; i++) {
        Collections.swap(list, i, i + 1);
    }
} else {
    for (int i = fromPosition; i > toPosition; i--) {
        Collections.swap(list, i, i - 1);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!