Add swipe right to delete ListView item

Fra87 picture Fra87 · Oct 17, 2016 · Viewed 20.8k times · Source

I have a ListView that uses a custom adaper (that extends BaseAdapter). How do I add the swipe to delete gesture?

I want use the same functionality the gmail application uses.

Answer

Gary Bak picture Gary Bak · Oct 17, 2016

The easiest way to do this is to move your ListView over to a RecyclerView and use a GridLayoutManager with a single column. It will look the same, but allows you to swipe to dismiss using the ItemTouchHelper.

     recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
     recyclerView.setLayoutManager(new GridLayoutManager(getActivity(), 1));

     recyclerView.setAdapter(adapter);


    ItemTouchHelper itemTouchHelper = new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
        @Override
        public void onSwiped(RecyclerView.ViewHolder viewHolder, int swipeDir) {
            // Remove item from backing list here
            adapter.notifyDataSetChanged();
        }
    });

    itemTouchHelper.attachToRecyclerView(recyclerView);