- Swipe to Delete and Undo in Android RecyclerView
- What we are going to build in this article?
- Step by Step Implementation
- Android RecyclerView: How to Insert, Update and Delete Item
- Why use RecyclerView in the first place ?
- How to use RecyclerView
- Adding recyclerview dependency
- Creating layout for RecyclerView
- LayoutManager in RecyclerView
- Preparing a ViewHolder
- Creating Product Model
- Creating interface for CUD
- Creating RecyclerView Adapter
- Declaring List to hold item detail
- getItemCount()
- onBindViewHolder()
- onCreateViewHolder()
- Add item
- Update item
- Remove item
- Auto generating ID
- Summary
- Using the RecyclerView Adapter
- Creating necessary variables
- Creating the item
- Updating the item
- Summary
Swipe to Delete and Undo in Android RecyclerView
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
Источник
Android RecyclerView: How to Insert, Update and Delete Item
RecyclerView is possibly most used View in Android development for showing list of items. There was something called ListView the use of which is now outdated. It is not deprecated but RecyclerView does much better task of managing list of thousands of items. It is because of the View Holder pattern. In this blog post we will see how we can use Android RecyclerView to insert, update and delete items in it.
Here we will be adding updating and removing some Product. So everything will be based around hypothetical Store. To follow along you must have a basic grasp of Android. With that being said let us start now.
Why use RecyclerView in the first place ?
If you have just started out with Android Development, this might be a general question on your mind.
It is because RecyclerView does a much better memory management out of the box. No matter the amount of items you have in your Adapter. RecyclerView will show only the items which the user is currently looking at.
Also it is worth noting RecyclerView is really much more straight froward once you grasp the basic idea behind it.
How to use RecyclerView
Let us first see what are the steps that we must go through in order to implement RecyclerView. Let us first see what we will be needing to make RecyclerView display items in list.
- First, we must create a RecyclerView instance in the XML layout
- Then, we will need to create a RecyclerView.Adapter implementation
- RecyclerView.Adapter requires a RecyclerView.ViewHolder to isolate each row and better mange them
- Then, we will define an Interface to add update and remove item values
- Finally, we will need our item as a POJO or any form you like
Let us look at how to implement these things one by one. But beware this is a really simple and basic RecyclerView implementation.
Adding recyclerview dependency
We have to add the following dependency in our app > build.gradle file before we can use RecyclerView .
This will enable us to use RecyclerView in our application. I have created a simple UI like below to add Product and it’s price.
Creating layout for RecyclerView
See the code for activity_main.xml below:
The UI from the above code is something like below.
And map the views to activity like this :
Focus on the highlighted lines as you need to map RecyclerView and also add some other properties.
.setHasFixedSize(true) tells the system that we will not be manipulating row height and width dynamically. It will make the operation a little bit faster.
We have to have a LayoutManager for our RecyclerView to display items in a list. Before we can use Android RecyclerView to insert, update and delete items. Let us look at what are the available layout managers.
LayoutManager in RecyclerView
If you are quite new to Android development you might not know that there are 3 layout managers built in for us to use with RecyclerView. Which are:
- LinearLayoutManager , when we want to show items as a simple list
- GridLayoutManager , when we want to show items in a grid
- StaggeredGridLayoutManager , when we want to show uneven grids
We will look at these separately but for this post we will be using only the LinearLayoutManager . And it’s usage is pretty straight forward.
We create an instance by simply doing : LinearLayoutManager(this) . Which we have already done in the highlighted text in above section.
Preparing a ViewHolder
Let us first prepare a ViewHolder before we move forward to our Adapter. It is really very simple.
Create a layout file in your res > layout folder and name it item_product .
Eveything is straightforward except for maybe the app:srcCompat=»@drawable/ic_delete_24″ portion. You can use the image of your choice.
Or just use the available vector image from android drawable. Right click on res > drawable then new > vector asset and follow.
For the code portion create a class named ProductListAdapter and copy the code below.
You will receive errors but don’t worry. It’s because of me explaining it in portions. We will remove the errors step by step.
The ViewHolder is the inner class ProductViewHolder and not the class ProductListAdapter .
I like to nest my ViewHolder class but you can extract it into a separate file in your other projects.
Also, itemView: View is the root view for each row which we will be using later. For now everything is mapped just like in the MainActivity class.
Creating Product Model
To store our simple data we first need to define a simple model class. It is just the POJO if you are familiar with java. For the sake of simplicity I am calling it model in this post.
Create a data class with the following code.
We will be using id to uniquely identify each item in the list. This will be useful when updating item later. Alongside we will be displaying name and price .
Creating interface for CUD
C = Create, U = Update, D = Delete
We will be creating an interface to communicate between Adapter and Activity. As it is generally a bad idea to put each and every logic inside the adapter. Let us first create an interface named OnProductClickListener .
We will be using this to show new items in the list. Let us move on with our Adapter.
Those were the prerequisite for use of Android RecyclerView to insert, update and delete items in list.
Creating RecyclerView Adapter
Now that we have created our ViewHolder and almost everything for adapter to use let us implement the adapter.
We have created the class ProductListAdapter let us continue there. We need to implement certain methods before we can actually code any further.
Lets see below I have left out the ViewHolder class for the sake of simplicity.
Let me explain each method in brief.
onCreateViewHolder() is where we create a new instance of ViewHolder and return it.
onBindViewHolder() is where we will map the data to the views as it is called each time the user does something on the screen.
Do not initialize any listeners here, generally considered a bad practice as it will harm the performance.
Finally, getItemCount() is where we return the number of items the Adapter will hold at any given time. Will most likely be called when we do invoke notifyDataSetChanged() or related methods.
Let us fill in the body for each one by one. Let us start by
Declaring List to hold item detail
You must modify the ProductListAdapter ‘s constructor and change it as following.
We will be using mContext to create the view we have defined above in the view holder i.e. item_product.xml .
And we will be storing all our data in mProductList variable.
The modified constructor of the class will look something like.
mOnProductClickListener will be used when we want to perform some actions in each row i.e. update or delete. More on this later as you follow along.
getItemCount()
This method is called by the adapter to determine total items whenever a new data set is passed in.
We will return the total size of the mProductList in this method. Change the above method to make it look like below
onBindViewHolder()
Here, the data is bind to the view. As the working mechanism of RecyclerView is optimized. It will create only the visible views to user.
So every time the user scrolls or does something. It will intelligently perform binding.
You must change the code of the method to this.
Remember the ViewHolder we created above ? We will be using .setText() to set the current position’s value. The value is in product .
onCreateViewHolder()
We will do a little bit of tasks here. Add some click listeners and add fairly simple logic.
Replace the method above with the code below. I will provide explanation based on line number so keep looking at code for reference.
Line 2 will create an inflater object. Which we use at Line 3 to inflate the view. And finally the ViewHolder which we defined earlier will be created at Line 4 .
Line 7 is where we have set click listener to the root view. Because when we click the row, we should pass data back to the input box.
Line 10 is where we will get the actual position of the view holder. This position is different from the onBindViewHolder() ‘s position because in onBindViewHolder() a relative position is passed in.
At Line 14 we have used .substringAfterLast() to remove the Rs. prefix from the string. Which we have set in onBindViewHolder() above.
Line 15 is where the actual magic happens. We invoke the onUpdate() method and pass in the actual position with the model . We will see to use in in later sections.
Line 19 to Line 23 is for deletion of item from the adapter. It is similar to update section described above.
We need to add certain methods in the Adapter before continuing with using the adapter.
Add item
We will need to add each items the code for looks like below. Add the method below in your adapter class.
We have used notifyItemInserted(mProductList.size) instead of the notifyDataSetChanged() method. It is because we want to update only one item and not the whole data set.
The performance difference will be noticeable when there are 1000’s of items in the list.
Update item
To update item we will be using similar method but we will be using notifyItemChanged() method instead of notifyItemInserted(mProductList.size) .
Let us look at the code below
We loop through each item and compare the id of it. If the item is found we replace the model at that position and notify that item has changed.
Remove item
Similarly we remove item with the method below. Add it too to the adapter class.
First we get the position and then remove the item from the list. And then we will notify that the item has been removed at that position with notifyItemRemoved() .
Finally we only have one more method to auto increment and get the id for each item.
Auto generating ID
It’s tiring to create one id manually each time so let us automate the process. This ID will be used to uniquely identify each item in the list. Which will help us in updating the values.
The logic is pretty straight forward. We will check if the list is empty. If it is not get the last item’s id and return it after doing +1 .
Summary
Let us take a look at final code of our RecyclerView.Adapter class including the ViewHolder .
Now that we have created the adapter. Let us use it in our activity. We are only left with final step in using Android RecyclerView for insert, update and delete.
Using the RecyclerView Adapter
Finally we have passed the most tiring bit of code and come to the almost end.
Let us see how we can use the ProductListAdapter in our application. I will break it down for you and there is a complete code below if you just want to see the code.
Creating necessary variables
Declare the following variables in the MainActivity class
Them mOnProductClickListener is the listener we had defined earlier. I have added comments above for you to easily understand it.
We also create and use a new instance of the adapter in the onCreate() method like below.
Creating the item
Let us first create the item and add it to the adapter.
Add the following click listener to the addProduct() variable in the MainActivity .
We have only done basic validation and got the next id for the list. Then we have created a new object of the ProductModel by passing in id , name and price .
And then called the addProduct() method of the adapter. Finally, we have cleared the input with .setText(«») .
Let us see the click listener for the update portion.
Updating the item
Add a listener to the variable updateProduct() in MainActivity.
Most of the things are same from the create item. The only difference is in the model variable. Instead of creating the new variable we have taken it from the modelToBeUpdated variable we have defined earlier.
Once we have new values set we passed the model to the adapter by calling updateProduct() method.
Summary
We have the final code for our MainActivity as below cross verify if you have missed anything at all.
That is how you use the adapter after creating it. If you want to look at the full source code visit this GitHub repository.
With this we have completed using Android RecyclerView for insert, update and delete item from it.
Feel free to comment below if you have any issue with this blog post or the code in the repository about android recyclerview .
Источник