Confirmation and undo removing in RecyclerView

后端 未结 4 2021
粉色の甜心
粉色の甜心 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:02

    I agree with @Gabor that it is better to soft delete the items and show the undo button.

    However I'm using Snackbar for showing the UNDO. It was easier to implement for me.

    I'm passing the Adapter and the RecyclerView instance to my ItemTouchHelper callback. My onSwiped is simple and most of the work is done by adapter.

    Here is my code (edited 2016/01/10):

    @Override
    public void onSwiped(RecyclerView.ViewHolder viewHolder, int direction) {
        mAdapter.onItemRemove(viewHolder, mRecyclerView);
    }
    

    The onItemRemove methos of the adapter is:

       public void onItemRemove(final RecyclerView.ViewHolder viewHolder, final RecyclerView recyclerView) {
        final int adapterPosition = viewHolder.getAdapterPosition();
        final Photo mPhoto = photos.get(adapterPosition);
        Snackbar snackbar = Snackbar
                .make(recyclerView, "PHOTO REMOVED", Snackbar.LENGTH_LONG)
                .setAction("UNDO", new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        int mAdapterPosition = viewHolder.getAdapterPosition();
                        photos.add(mAdapterPosition, mPhoto);
                        notifyItemInserted(mAdapterPosition);
                        recyclerView.scrollToPosition(mAdapterPosition);
                        photosToDelete.remove(mPhoto);
                    }
                });
        snackbar.show();
        photos.remove(adapterPosition);
        notifyItemRemoved(adapterPosition);
        photosToDelete.add(mPhoto);
    }
    

    The photosToDelete is an ArrayList field of myAdapter. I'm doing the real delete of those items in onPause() method of the recyclerView host fragment.

    Note edit 2016/01/10:

    • changed hard-coded position as @Sourabh suggested in comments
    • for the complete example of adapter and fragment with RV see this gist

提交回复
热议问题