Confirmation and undo removing in RecyclerView

后端 未结 4 2030
粉色の甜心
粉色の甜心 2020-12-24 12:22

I have got a list of simple items in RecyclerView. Using ItemTouchHelper it was very easy to implement \"swipe-to-delete\" behavior.

public class TripsAdapte         


        
4条回答
  •  别那么骄傲
    2020-12-24 13:03

    I've figured out much simpler way to do a deletion confirmation dialog working:

    @Override
            public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
                int itemPosition = viewHolder.getAdapterPosition();
    
                new AlertDialog.Builder(YourActivity.this)
                        .setMessage("Do you want to delete: \"" + mRecyclerViewAdapter.getItemAtPosition(itemPosition).getName() + "\"?")
                        .setPositiveButton("Delete", (dialog, which) -> mYourActivityViewModel.removeItem(itemPosition))
                        .setNegativeButton("Cancel", (dialog, which) -> mRecyclerViewAdapter.notifyItemChanged(itemPosition))
                        .setOnCancelListener(dialogInterface -> mRecyclerViewAdapter.notifyItemChanged(itemPosition))
                        .create().show();
            }
    

    Note that:

    • deletion is delegated to ViewModel which updates the mRecyclerViewAdapter upon success.
    • for the item to "return" you just have to call mRecyclerViewAdapter.notifyItemChanged
    • cancelListener and negativeButtonListener perform the same thing. You can opt to use .setCanclable(false) if you don't want the user to tap outside the dialog

提交回复
热议问题