Swipe to Delete and Undo in Android RecyclerView
Last Updated :
01 Aug, 2024
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.
What we are going to build in this article?
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 by Step Implementation
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.
Output:
Similar Reads
Android - Swipe to Delete and Undo in RecyclerView with Kotlin
We have seen many android applications in which data is being displayed in the form of a list. If we want to delete any item from that recycler view we can simply swipe that item to delete it. We can see this type of feature in the Gmail application in which when an email is swiped to the right it i
7 min read
RecyclerView in Android with Example
RecyclerView is a ViewGroup added to the android studio as a successor of the GridView and ListView. It is an improvement on both of them and can be found in the latest v-7 support packages. It has been created to make possible construction of any lists with XML layouts as an item which can be custo
7 min read
How to Update RecyclerView Adapter Data in Android?
RecyclerView is used in many android applications to display the list of data within android applications. We can dynamically add or remove data from our recycler view. For updating data in the RecyclerView, we have to use the Adapter class. Adapter handles all the data within our recycler view. In
6 min read
How to Add Dividers in Android RecyclerView?
In the article Android RecyclerView in Kotlin, it's been demonstrated how to implement the Recycler View in Android. But in the case of User Experience, the items need to be distinguished with the divider and proper padding and margins in each item. In this case, the Recycler View Item Decoration co
8 min read
How to Disable RecyclerView Scrolling in Android?
RecyclerView is a view group used for displaying data from arrays and databases. RecyclerView basically is a list of items from the data. RecyclerView is often referred to as a successor of GridView and ListView. More about RecyclerView could be found at RecyclerView in Android with Example. Recycle
3 min read
How to Use SnapHelper in RecyclerView in Android?
SnapHelper is an amazing feature that is seen in RecyclerView. With the help of this feature, we can make the items of the RecyclerView properly visible. This feature of Recycler View is present in most of the apps, but it is not visible. This feature is generally seen in the Google Play application
6 min read
Endless RecyclerView in Android
In this article, we are going to see how to build an endless RecyclerView in Android Studio. It is mostly used to design the user interface with great control over the lists and grids of android applications. We can implement both horizontal and vertical layouts using RecyclerView. Here, we will be
6 min read
Android | Horizontal RecyclerView with Examples
Recycler View is a ViewGroup added to Android Studio as a successor of the GridView and ListView. It is an improvement on both of them and can be found in the latest v-7 support packages. It has been created to make possible construction of any lists with XML layouts as an item which can be customiz
4 min read
How to Add Drag And Drop Feature in Android RecyclerView?
Drag And Drop feature is very helpful. It is very simple and easy to implement. It is used in many apps that are famous, and if we're doing some project it is very convenient to implement it. You should know the RecyclerAdapter Class. A sample video is given below to get an idea about what we are go
4 min read
CardView using RecyclerView in Android with Example
RecyclerView is an extended version of ListView and GridView. It works on the ViewHolder design pattern. With the help of RecyclerView, we can add many extra features to our list of data. Before starting our example on the implementation of CardView in RecyclerView. We should know what CardView and
9 min read