Android - Swipe to Delete and Undo in RecyclerView with Kotlin
Last Updated :
08 Aug, 2022
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 is moved to the archive. In this article, we will be building a simple recycler view and implementing a swipe to delete and undo the RecyclerView item in Kotlin. A sample video is given below to get an idea about what we are going to do in this article.
Note: If you are looking to implement Swipe to Delete and Undo items of Recycler View in Java. Check out the following article: Swipe to Delete and Undo items of Recycler View in Android with Java
Step by Step Implementation
Step 1: Create a New Project in Android Studio
To create a new project in Android Studio please refer to How to Create/Start a New Project in Android Studio. Note that select Kotlin as the programming language.
Step 2: Create a Card Layout for Recycler View Card Items
Go to the app > res > layout> right-click > New >Layout Resource File and name the file as course_rv_item. In this file, all XML code related to card items in the RecyclerView is written. Below is the code for the course_rv_item.xml file.
XML
<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="5dp"
app:cardCornerRadius="5dp"
app:cardElevation="4dp">
<!--on below line we are creating a
linear layout for grid view item-->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal">
<!--on below line we are creating
a simple image view-->
<ImageView
android:id="@+id/idIVCourse"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_gravity="center"
android:layout_margin="8dp"
android:padding="5dp"
android:src="@mipmap/ic_launcher" />
<!--on below line we are creating
a simple text view-->
<TextView
android:id="@+id/idTVCourse"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_margin="5dp"
android:padding="4dp"
android:text="@string/app_name"
android:textAlignment="textStart"
android:textColor="@color/black"
android:textStyle="bold"
tools:ignore="RtlCompat" />
</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 > Kotlin Class and name the file as CourseRVModal. Add the below code to it. Comments are added in the code to get to know in detail.Â
Kotlin
package com.gtappdevelopers.kotlingfgproject
data class CourseRVModal(
// on below line we are creating a
// two variable one for course
// name and other for course image
var courseName: String,
var courseImg: Int
)
Step 4: Create a new Kotlin class for the Adapter
Similarly, create a new Java Class and name the file as CourseRVAdapter. The adapter is the main class that is responsible for RecyclerView. It holds all methods which are useful in RecyclerView. The Adapter class is used to set the data to each item of our recycler view.Â
Kotlin
package com.gtappdevelopers.kotlingfgproject
import android.content.Context
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.ImageView
import android.widget.TextView
import androidx.recyclerview.widget.RecyclerView
// on below line we are creating
// a course rv adapter class.
class CourseRVAdapter(
// on below line we are passing variables
// as course list and context
private val courseList: ArrayList<CourseRVModal>,
private val context: Context
) : RecyclerView.Adapter<CourseRVAdapter.CourseViewHolder>() {
override fun onCreateViewHolder(
parent: ViewGroup,
viewType: Int
): CourseRVAdapter.CourseViewHolder {
// this method is use to inflate the layout file
// which we have created for our recycler view.
// on below line we are inflating our layout file.
val itemView = LayoutInflater.from(parent.context).inflate(
R.layout.course_rv_item,
parent, false
)
// at last we are returning our view holder
// class with our item View File.
return CourseViewHolder(itemView)
}
override fun onBindViewHolder(holder: CourseRVAdapter.CourseViewHolder, position: Int) {
// on below line we are setting data to our text view and our image view.
holder.courseNameTV.text = courseList.get(position).courseName
holder.courseIV.setImageResource(courseList.get(position).courseImg)
}
override fun getItemCount(): Int {
// on below line we are returning
// our size of our list
return courseList.size
}
class CourseViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
// on below line we are initializing our course name
// text view and our image view.
val courseNameTV: TextView = itemView.findViewById(R.id.idTVCourse)
val courseIV: ImageView = itemView.findViewById(R.id.idIVCourse)
}
}
Step 5: Working with the activity_main.xml file
This is the main screen that displays all data in the form of a grid. Here we have to implement Recycler View. Below is the code snippet of the XML layout in 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"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context=".MainActivity">
<!--on below line we are creating a
text for heading of our app-->
<TextView
android:id="@+id/idTVHeading"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="8dp"
android:gravity="center"
android:padding="4dp"
android:text="Swipe to Delete and Undo"
android:textAlignment="center"
android:textColor="@color/purple_200"
android:textSize="18sp"
android:textStyle="bold" />
<!--on below line we are creating a recycler view-->
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/idRVCourses"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_below="@id/idTVHeading" />
</RelativeLayout>
Step 6: Working with the MainActivity.kt file
Navigate to app>java>your app's package name>MainActivity.kt file and add the below code to it. Comments are added in the code to get to know in detail.Â
Kotlin
package com.gtappdevelopers.kotlingfgproject
import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.ItemTouchHelper
import androidx.recyclerview.widget.RecyclerView
import com.google.android.material.snackbar.Snackbar
class MainActivity : AppCompatActivity() {
// on below line we are creating variables for
// our swipe to refresh layout, recycler view, adapter and list.
lateinit var courseRV: RecyclerView
lateinit var courseRVAdapter: CourseRVAdapter
lateinit var courseList: ArrayList<CourseRVModal>
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
// on below line we are initializing
// our views with their ids.
courseRV = findViewById(R.id.idRVCourses)
// on below line we are initializing our list
courseList = ArrayList()
// on below line we are initializing our adapter
courseRVAdapter = CourseRVAdapter(courseList, this)
// on below line we are setting adapter
// to our recycler view.
courseRV.adapter = courseRVAdapter
// on below line we are adding data to our list
courseList.add(CourseRVModal("Android Development", R.drawable.android))
courseList.add(CourseRVModal("C++ Development", R.drawable.c))
courseList.add(CourseRVModal("Java Development", R.drawable.java))
courseList.add(CourseRVModal("Python Development", R.drawable.python))
courseList.add(CourseRVModal("JavaScript Development", R.drawable.js))
// on below line we are notifying adapter
// that data has been updated.
courseRVAdapter.notifyDataSetChanged()
// 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
// 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
ItemTouchHelper(object : ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.RIGHT) {
override fun onMove(
recyclerView: RecyclerView,
viewHolder: RecyclerView.ViewHolder,
target: RecyclerView.ViewHolder
): Boolean {
// this method is called
// when the item is moved.
return false
}
override fun onSwiped(viewHolder: RecyclerView.ViewHolder, direction: Int) {
// this method is called when we swipe our item to right direction.
// on below line we are getting the item at a particular position.
val deletedCourse: CourseRVModal =
courseList.get(viewHolder.adapterPosition)
// below line is to get the position
// of the item at that position.
val position = viewHolder.adapterPosition
// this method is called when item is swiped.
// below line is to remove item from our array list.
courseList.removeAt(viewHolder.adapterPosition)
// below line is to notify our item is removed from adapter.
courseRVAdapter.notifyItemRemoved(viewHolder.adapterPosition)
// below line is to display our snackbar with action.
// below line is to display our snackbar with action.
// below line is to display our snackbar with action.
Snackbar.make(courseRV, "Deleted " + deletedCourse.courseName, Snackbar.LENGTH_LONG)
.setAction(
"Undo",
View.OnClickListener {
// adding on click listener to our action of snack bar.
// below line is to add our item to array list with a position.
courseList.add(position, deletedCourse)
// below line is to notify item is
// added to our adapter class.
courseRVAdapter.notifyItemInserted(position)
}).show()
}
// at last we are adding this
// to our recycler view.
}).attachToRecyclerView(courseRV)
}
}
Now run your application to see the output of it.Â
Output:Â
Similar Reads
Architecture of 8085 microprocessor
A microprocessor is fabricated on a single integrated circuit (IC) or chip that is used as a central processing unit (CPU).The 8085 microprocessor is an 8-bit microprocessor that was developed by Intel in the mid-1970s. It was widely used in the early days of personal computing and was a popular cho
11 min read
Android Architecture
Android architecture contains a different number of components to support any Android device's needs. Android software contains an open-source Linux Kernel having a collection of a number of C/C++ libraries which are exposed through application framework services. Among all the components Linux Kern
5 min read
States of a Process in Operating Systems
In an operating system, a process is a program that is being executed. During its execution, a process goes through different states. Understanding these states helps us see how the operating system manages processes, ensuring that the computer runs efficiently. Please refer Process in Operating Sys
11 min read
Android Tutorial
In this Android Tutorial, we cover both basic and advanced concepts. So whether you are a fresher (graduate) or an experienced candidate with several years of Android Development experience, you can follow this Android tutorial to kick-start your journey in Android app development. Our Android Tutor
15+ min read
Activity Lifecycle in Android with Demo App
In Android, an activity is referred to as one screen in an application. It is very similar to a single window of any desktop application. An Android app consists of one or more screens or activities. Each activity goes through various stages or a lifecycle and is managed by activity stacks. So when
9 min read
Introduction to Android Development
Android operating system is the largest installed base among various mobile platforms across the globe. Hundreds of millions of mobile devices are powered by Android in more than 190 countries of the world. It conquered around 71% of the global market share by the end of 2021, and this trend is grow
5 min read
Android UI Layouts
Layouts in Android define the user interface and hold UI controls or widgets that appear on the screen of an application. Every Android application consists of View and ViewGroup elements. Since an application contains multiple activitiesâeach representing a separate screenâevery activity has multip
5 min read
Top 50 Android Interview Questions and Answers - SDE I to SDE III
A Linux-based open-source OS, Android was created by Andy Rubin and became one of the most popular smartphone operating systems. With 71 percent of the market share worldwide, Android is on top. Because it is on top in the smartphone OS, Android development is always in demand.If you are seeking a j
15+ min read
Components of an Android Application
There are some necessary building blocks that an Android application consists of. These loosely coupled components are bound by the application manifest file which contains the description of each component and how they interact. The manifest file also contains the appâs metadata, its hardware confi
3 min read
Kotlin Tutorial
This Kotlin tutorial is designed for beginners as well as professional, which covers basic and advanced concepts of Kotlin programming language. In this Kotlin tutorial, you'll learn various important Kotlin topics, including data types, control flow, functions, object-oriented programming, collecti
4 min read