How to do swipe gesture on RecyclerView item witho

2019-03-12 20:25发布

问题:

Is their any direct support for slide to delete/archive (right to left or left to right) on RecyclerView item.

And instead of delete/archive I want four buttons under the list item.

something like this https://github.com/47deg/android-swipelistview but for recyclerview and official support not any 3rd party lib

回答1:

Yes there is, you can do it with ItemTouchHelper class provided by the support library.

P.S. I had to do this the other day and also wanted to avoid using 3rd party lib if possible. The library might be doing much more than you need and because of that it might be more complex than necessary in your case. It can also unnecessary grow your method count. This is just a sample of reasons why you should avoid adding lib as a quick fix for your problem.

EDIT: I had a go at this, see this blog post and this github repo.



回答2:

Yes there is. Use ItemTouchHelper. Try to clone this project and see how it is used.

For specific file, see line 87

For lazy people who don't want to click links, this is how you setup:

    ItemTouchHelper.SimpleCallback simpleCallback =
            new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT) {
                @Override
                public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder,
                                      RecyclerView.ViewHolder target) {
                    return false;
                }

                @Override
                public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
                    //do things
                }
            };

    ItemTouchHelper itemTouchHelper = new ItemTouchHelper(simpleCallback);
    itemTouchHelper.attachToRecyclerView(recyclerView);

The recyclerView is the variable holding recycler view.

There are other directions aside from ItemTouchHelper.RIGHT, try to experiment.