Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to swap item from one section to another section and vice versa in Recycler view?

I have a RecyclerView and I want to show that RecyclerView with two sections. First time section one will be empty and I want to drag item from section two to section one. When item is added to section one and it should be deleted from section two and vice versa.

Please help me friends.RecyclerView

like image 756
Vishal Avatar asked Jul 22 '16 02:07

Vishal


People also ask

How do I use ItemTouchHelper Simplecallback?

A simple wrapper to the default Callback which you can construct with drag and swipe directions and this class will handle the flag callbacks. You should still override onMove or onSwiped depending on your use case. final int fromPos = viewHolder.

How do I remove a space between two items in RecyclerView?

Try to use cardElevation=0dp. This should remove the extra spacing between recyclerview items.


1 Answers

Try this,it worked with me in my app,

In your adapter class put this below code,

here MessageList is name of the Arraylist,

public void swap(int firstPosition, int secondPosition)
{
    Collections.swap(MessageList, firstPosition, secondPosition);
    notifyItemMoved(firstPosition, secondPosition);
}  

now add this small class separately,

here Adapter is name of the Adapter class put your adapter name

public class MovieTouchHelper extends ItemTouchHelper.SimpleCallback {
    Aadapter recycleAdapter;

    public MovieTouchHelper(Aadapter recycleAdapter) {
        super(ItemTouchHelper.UP | ItemTouchHelper.DOWN, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT);
        this.recycleAdapter = recycleAdapter;
    }

    @Override
    public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {
        recycleAdapter.swap(viewHolder.getAdapterPosition(), target.getAdapterPosition());
        return true;
    }

    @Override
    public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
        recycleAdapter.remove(viewHolder.getAdapterPosition());
    }
}

Then in your mainActivity where you defined recycleview,

ItemTouchHelper.Callback callback = new MovieTouchHelper(adapter);
ItemTouchHelper helper = new ItemTouchHelper(callback);
helper.attachToRecyclerView(rv_list);

here rv_list is name of recycleview.

Follow this steps and if you find any problem or you can't swip items then directly tell me...

See this GIF

enter image description here

like image 93
bhumika rijiya Avatar answered Oct 01 '22 02:10

bhumika rijiya