Search code examples
androidlistviewswipe

Add swipe right to delete ListView item


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.


Solution

  • 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);