Swipe to Delete and Undo in Android RecyclerView

05 Oct, 2021
We have seen many apps having a RecyclerView present in them and along with that, we have seen many functionalities in that RecyclerView for swipe to delete and many more. We have seen this type of feature in Gmail apps where we can swipe or item right or left to delete or add to the archive. In this article, we will take a look at the implementation of Swipe to Delete RecyclerView items in Android with Undo functionality in it. 
We will be building a simple application in which we will be displaying a simple RecyclerView which displays a list of courses along with its description and we will be adding functionality for swipe to delete and undo to it. A sample GIF is given below to get an idea about what we are going to do in this article. Note that we are going to implement this project using the Java language. 
Step 1: Create a New Project
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Java as the programming language.
To implement Recycler View three sub-parts are needed which are helpful to control RecyclerView. These three subparts include:  
Card Layout: The card layout is an XML file that will represent each individual grid item inside your Recycler view.
View Holder: View Holder Class is the java class that stores the reference to the UI Elements in the Card Layout and they can be modified dynamically during the execution of the program by the list of data.
Data Class: Data Class is an object class that holds information to be displayed in each recycler view item that is to be displayed in Recycler View.
Step 2: Create a Card Layout for RecyclerView Card Items
Go to the app > res > layout> right-click > New > Layout Resource File and name the file as card_layout. In this file, all XML code related to card items in the RecyclerView is written. Below is the code for the card_layout.xml file.
XML
<?xml version="1.0" encoding="utf-8"?><!--XML implementation of Card Layout--><androidx.cardview.widget.CardView    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:app="http://schemas.android.com/apk/res-auto"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:layout_margin="5dp"    app:cardCornerRadius="5dp"    app:cardElevation="5dp">     <LinearLayout        android:layout_width="match_parent"        android:layout_height="wrap_content"        android:layout_margin="3dp"        android:orientation="vertical">         <!--text view for displaying our course name-->        <TextView            android:id="@+id/idTVCourseName"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:layout_margin="2dp"            android:padding="5dp"            android:text="Course Name"            android:textColor="@color/black" />         <!--text view for displaying            our course description-->        <TextView            android:id="@+id/idTVCourseDesc"            android:layout_width="match_parent"            android:layout_height="wrap_content"            android:layout_margin="2dp"            android:padding="5dp"            android:text="Course Description"            android:textColor="@color/black" />     </LinearLayout> </androidx.cardview.widget.CardView>
 
 
Step 3: Create a Java class for Modal Data
 
Go to the app > java > Right-Click on your app’s package name > New > Java Class and name the file as RecyclerData. This class will handles data for each Recycler item that is to be displayed. Below is the code for the RecyclerData.java file.
 
Java
public class RecyclerData {    // string for displaying    // title and description.    private String title;    private String description;     // constructor for our title and description.    public RecyclerData(String title, String description) {        this.title = title;        this.description = description;    }     // creating getter and setter methods.    public String getTitle() {        return title;    }     public void setTitle(String title) {        this.title = title;    }     public String getDescription() {        return description;    }     public void setDescription(String description) {        this.description = description;    }  }
 
 
Step 4: Create a new java class for the Adapter
 
Similarly, create a new Java Class and name the file as RecyclerViewAdapter. The adapter is the main class that is responsible for RecyclerView. It holds all methods which are useful in RecyclerView.  
 
Note: View Holder Class is also implemented in Adapter Class itself.  
 
These methods to handle Recycler View includes:  
 
onCreateViewHolder: This method inflates card layout items for Recycler View.
onBindViewHolder: This method sets the data to specific views of card items. It also handles methods related to clicks on items of Recycler view.
getItemCount: This method returns the length of the RecyclerView.
 
Below is the code for the RecyclerViewAdapter.java file. Comments are added inside the code to understand the code in more detail.
 
Java
import android.content.Context;import android.view.LayoutInflater;import android.view.View;import android.view.ViewGroup;import android.widget.TextView; import androidx.annotation.NonNull;import androidx.recyclerview.widget.RecyclerView; import java.util.ArrayList; public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.RecyclerViewHolder> {     // creating a variable for our array list and context.    private ArrayList<RecyclerData> courseDataArrayList;    private Context mcontext;     // creating a constructor class.    public RecyclerViewAdapter(ArrayList<RecyclerData> recyclerDataArrayList, Context mcontext) {        this.courseDataArrayList = recyclerDataArrayList;        this.mcontext = mcontext;    }     @NonNull    @Override    public RecyclerViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {        // Inflate Layout        View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.card_layout, parent, false);        return new RecyclerViewHolder(view);    }     @Override    public void onBindViewHolder(@NonNull RecyclerViewHolder holder, int position) {        // Set the data to textview from our modal class.        RecyclerData recyclerData = courseDataArrayList.get(position);        holder.courseNameTV.setText(recyclerData.getTitle());        holder.courseDescTV.setText(recyclerData.getDescription());    }     @Override    public int getItemCount() {        // this method returns          // the size of recyclerview        return courseDataArrayList.size();    }     // View Holder Class to handle Recycler View.    public class RecyclerViewHolder extends RecyclerView.ViewHolder {               // creating a variable for our text view.        private TextView courseNameTV;        private TextView courseDescTV;         public RecyclerViewHolder(@NonNull View itemView) {            super(itemView);            // initializing our text views.            courseNameTV = itemView.findViewById(R.id.idTVCourseName);            courseDescTV = itemView.findViewById(R.id.idTVCourseDesc);        }    }}
 
 
Step 5: Working with the activity_main.xml file
 
Navigate to the app > res > layout > activity_main.xml and add the below code to that file. Below is the code for the activity_main.xml file. 
 
XML
<?xml version="1.0" encoding="utf-8"?><RelativeLayout    xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools="http://schemas.android.com/tools"    android:layout_width="match_parent"    android:layout_height="match_parent"    android:layout_gravity="center"    android:gravity="center"    android:orientation="vertical"    tools:context=".MainActivity">     <!--creating a recycler view for        displaying our list of courses-->    <androidx.recyclerview.widget.RecyclerView        android:id="@+id/idRVCourse"        android:layout_width="match_parent"        android:layout_height="match_parent" />     </RelativeLayout>
 
 
Step 6: Working with the MainActivity.java file
 
Go to the MainActivity.java file and refer to the following code. Below is the code for the MainActivity.java file. Comments are added inside the code to understand the code in more detail.
 
Java
import android.os.Bundle;import android.view.View; import androidx.annotation.NonNull;import androidx.appcompat.app.AppCompatActivity;import androidx.recyclerview.widget.ItemTouchHelper;import androidx.recyclerview.widget.LinearLayoutManager;import androidx.recyclerview.widget.RecyclerView; import com.google.android.material.snackbar.Snackbar; import java.util.ArrayList; public class MainActivity extends AppCompatActivity {         // creating a variable for recycler view,    // array list and adapter class.    private RecyclerView courseRV;    private ArrayList<RecyclerData> recyclerDataArrayList;    private RecyclerViewAdapter recyclerViewAdapter;     @Override    protected void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.activity_main);                 // initializing our variables.        courseRV = findViewById(R.id.idRVCourse);                 // creating new array list.        recyclerDataArrayList = new ArrayList<>();                 // in below line we are adding data to our array list.        recyclerDataArrayList.add(new RecyclerData("DSA Course", "DSA Self Paced Course"));        recyclerDataArrayList.add(new RecyclerData("C++ Course", "C++ Self Paced Course"));        recyclerDataArrayList.add(new RecyclerData("Java Course", "Java Self Paced Course"));        recyclerDataArrayList.add(new RecyclerData("Python Course", "Python Self Paced Course"));        recyclerDataArrayList.add(new RecyclerData("Fork CPP", "Fork CPP Self Paced Course"));        recyclerDataArrayList.add(new RecyclerData("Amazon SDE", "Amazon SDE Test Questions"));                // initializing our adapter class with our array list and context.        recyclerViewAdapter = new RecyclerViewAdapter(recyclerDataArrayList, this);                // below line is to set layout manager for our recycler view.        LinearLayoutManager manager = new LinearLayoutManager(this);                 // setting layout manager for our recycler view.        courseRV.setLayoutManager(manager);                 // below line is to set adapter        // to our recycler view.        courseRV.setAdapter(recyclerViewAdapter);                 // on below line we are creating a method to create item touch helper        // method for adding swipe to delete functionality.        // in this we are specifying drag direction and position to right        new ItemTouchHelper(new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT) {            @Override            public boolean onMove(@NonNull RecyclerView recyclerView, @NonNull RecyclerView.ViewHolder viewHolder, @NonNull RecyclerView.ViewHolder target) {                // this method is called                // when the item is moved.                return false;            }             @Override            public void onSwiped(@NonNull RecyclerView.ViewHolder viewHolder, int direction) {                // this method is called when we swipe our item to right direction.                // on below line we are getting the item at a particular position.                RecyclerData deletedCourse = recyclerDataArrayList.get(viewHolder.getAdapterPosition());                                 // below line is to get the position                // of the item at that position.                int position = viewHolder.getAdapterPosition();                                 // this method is called when item is swiped.                // below line is to remove item from our array list.                recyclerDataArrayList.remove(viewHolder.getAdapterPosition());                                 // below line is to notify our item is removed from adapter.                recyclerViewAdapter.notifyItemRemoved(viewHolder.getAdapterPosition());                                 // below line is to display our snackbar with action.                Snackbar.make(courseRV, deletedCourse.getTitle(), Snackbar.LENGTH_LONG).setAction("Undo", new View.OnClickListener() {                    @Override                    public void onClick(View v) {                        // adding on click listener to our action of snack bar.                        // below line is to add our item to array list with a position.                        recyclerDataArrayList.add(position, deletedCourse);                                                 // below line is to notify item is                        // added to our adapter class.                        recyclerViewAdapter.notifyItemInserted(position);                    }                }).show();            }            // at last we are adding this            // to our recycler view.        }).attachToRecyclerView(courseRV);    }}
 
 
Now run your app and see the output of the app. 
 
 
varshagumber28
android
Picked
Technical Scripter 2020
Android
Java
Technical Scripter
Java
Android
Writing code in comment?
Please use ide.geeksforgeeks.org,
generate link and share the link here.