Intro

In this post we will demonstrate how to update an item in your RecyclerView. Updating an item in RecyclerView is useful when you are working with a list of elements that you will sent for example as a part of an API request, but the user has an option to alternate some or all of the elements in the list. For example you have a shopping card with items, but before the user goes to checkout he can make a change in the quantity of an item. Or you need to edit some name from a list you want to send to API.

Exercise

For this exercise we will use the project we created in the previous post, we will just create another branch and work there. In our exercise we have the following scenario: the user is able to click on an item in the RecyclerView, and on click we will display a popup dialog where the user can change and update the item name and save the changes.

First we will create the layout for the dialog. We will have an EditText where the user can enter the new item name, and also Save and Cancel buttons. The code for the layout will look like this:

Next we will need to implement the code to display the dialog on item click. We will use the same approach for the on click listener like we did in the previous post. We need to display the dialog on an RecyclerView item click event, so the code to display the dialog will go in our overridden onClickListener method in the activity, and it will look like this:

In order to update an item in the RecyclerView we will need to create a method in our adapter that will receive the items position and the new name that we want the item to have as parameters. We will change the value of the name on the item in the selected position and use notifyItemChange() method to update the RecyclerView. This is the code for this method:

Next we will need to setup the on click listeners for our save and cancel buttons in the dialog, so in the overridden onItemClickListener method we will add the following code:

Now we are ready to update an item in the RecyclerView. We click on item number four and enter a new name:

The result is an updated item:

You can get the whole project on GitHub here: https://github.com/AleksandarGulevski/RecyclerViewExercises/tree/UpdateItem

Happy coding!

Spread the love

Leave a Reply

Your email address will not be published. Required fields are marked *