Add swipe right to delete ListView item
23,959
Solution 1
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);
Solution 2
You can use the lib ::
Solution 3
Accepted answer translated to Kotlin:
val itemTouchHelper = ItemTouchHelper(object: ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT or ItemTouchHelper.RIGHT) {
override fun onMove(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder
): Boolean {
TODO("Not yet implemented")
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
todoListAdapter.notifyDataSetChanged()
}
})
this.runOnUiThread {
itemTouchHelper.attachToRecyclerView(recyclerView)
}
Author by
Fra87
Updated on July 20, 2022Comments
-
Fra87 almost 2 years
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.
-
Gary Bak over 7 yearsYes, you will have to change the ListView to a RecyclerView, change the adapter base class type and then create one or more Handlers for the data.
-
Fra87 over 7 yearsI have do it, but now i have scroll in recycleview, i don't want scroll i have already scrollview is possible remove scroll?
-
Fra87 over 7 yearsI have solved problem of scroll, my Adapter is RecyclerView.Adapter, if i want method that return item from position How i do?
-
Fra87 over 7 yearsi want to create my custom method delete in RecyclerView.Adapter but i have a dubt, after i have delete item from ArrayList then i call notifyDataSetChanged() or i call notifyItemRemoved() ?
-
Gary Bak over 7 yearsRemoved is probably the better choice, then the adapter knows which positions it has to redraw. The
notifyDataSetChanged
will force it to redraw whatever is on the screen. -
Fra87 over 7 yearsLast question: If i want add listner on item how i can?
-
Fra87 over 7 yearsFrom adapter is possible call onCreate activity?
-
zypro over 5 yearsthis repo is deprecated
-
Giorgio Barchiesi over 4 yearsShall also implement public boolean onMove(RecyclerView recyclerView, RecyclerView.ViewHolder viewHolder, RecyclerView.ViewHolder target) {return false;} Upvoted!
-
Bennik2000 over 3 yearsThis is an answer for flutter. However the question targets native android