Staggered Recyclerview With Multiple Selection in Kotlin

Martina Alinda
The Startup
Published in
5 min readSep 10, 2020

--

Created by Harryarts — www.freepix.com

The RecyclerView widget is currently the most popular way to display a large, complex lists in android applications.

In this article I’ll show you how to implement the Staggered RecyclerView with multiple selection in Kotlin. Staggered view is a way of displaying items in different proportions based on their dimensions.

Prerequisites

To follow along, you’ll need:

  • Some basic understanding of Android Studio
  • A device or emulator running Android API level 21 or higher
  • A new Android Studio project with an empty activity. You can create a new project and select the “Empty Activity” template

1. Add the android dependencies to your build.gradle file

2. Add a RecyclerView to the Layout

Add the RecyclerView tag to your activity_main.xml

Also create a new XML layout file called post_item_container to specify the layout of the list items. Our list items will contain a LinearLayout with a RoundedImageView widget inside.

Add the item_background.xml selector and selected_item_background.xml shape to show items that have been selected.

item_background.xml and selected_item_background.xml

3. Create a List of images

We will work with a small list of items each containing an image name (String) and the image resource id (Int).

Make sure the image name is unique as we’ll use the names to identify each item.

Create a Kotlin data class called PostItem to store the data of each list item, and add the two properties name and id (we’ll call id “image”)

Now download 10 random images of your choice to display in our RecyclerView and put them in your app/src/main/res/drawable folder. I went with pictures of some of my favorite Korean male actors.

Create a list of PostItem objects in the MainActivity

4. Display the List

To display our list of images we’ll need to create an Adapter. Adapters provide a binding from a specific data set to views that are displayed within a RecyclerView and they are called by the RecyclerViews to display data at a specific position. Your Adapter could look like this:

We’ll also need to initialize the RecyclerView in our MainActivity, set it’s layout manager and adapter. For the staggered view, use StaggeredGridLayoutManager and set the spanCount (number of columns) to 2, and the orientation to vertical. Check lines 12, 13 and 27 below.

At this point you are ready to display the list. Run the app on your emulator or device to check. Your setup should be similar to the master branch of my repository here.

5. Create a Selection Tracker

To enable multiple selection, we’ll need to add a SelectionTracker object in the Main Activity. We’ll initialize it using the SelectionTracker.Builder class and pass the following to its constructor:

  • Selection ID: Give the tracker a unique ID of your choice. This is necessary as an activity or fragment may have multiple distinct selectable lists
  • RecyclerView widget
  • ItemKeyProvider: We must decide on the key type to use to identify selected items. Support is provided for three types: Parcelable, String, and Long
  • ItemDetailsLookup: This provides the selection library access to information about items associated with the area under a MotionEvent
  • A StorageStrategy: This depends on the key type selected

I decided to use Parcelabletype as the key and so we have to convert the PostItem data class into a Parcelable. It will now look like this:

Next we’ll implement the ItemKeyProvider class. Create a new Kotlin class called MyItemKeyProvider and add the following..

For this to work we’ll need to add some functions in the PostsAdapter.

We need line 21 and 22 in the code above for the ItemKeyProvider and the function getItemDetails() on line 12 will be used in the ItemDetailsLookup we are implementing next. Create a new Kotlin class called MyItemDetailsLookup.

For the StorageStrategy, we’ll use the built in method: createParcelableStorage(Class). Our selection tracker will now look like this

6. Connect the Selection Tracker to the Adapter

The selection tracker is not very useful if it is not associated with our PostsAdapter, so we will create a public SelectionTracker variable in our adapter and also ensure selected items are activated to show the orange stroke. In the end your PostsAdapter should look like this

We’ll need to set the tracker in our adapter. Add line 24 in the MainActivity just below the tracker as shown below.

At this point if you run the app you should be able to select items in the list. Long press any item to enter selection mode.

7. Add an Observer

Ideally you would want to see how many items you have selected and also perform some actions on them. To do this associate a SelectionObserver object with the selection tracker by calling the addObserver() method. Inside the onSelectionChanged() method of the observer, you can detect changes in the items selected.

You can display the number of items any way you like. I prefer to use ActionMode. Action modes can be used to provide alternative interaction modes and replace/overlay parts of the normal UI, in ourcase the Toolbar. Don’t worry about ActionMode so much, you can get more information about it here.

Add an action mode menu in the app/src/main/res/menu/ folder.

I originally wanted to delete the selected items but changed my mind and decided to just show a Toast for demonstration purposes. Btw include line 3 below in your strings.xml resources file found in the app/src/main/res/values folder.

You can change the background color of the ActionModeBar to orange in the styles.xml resources file also found in the app/src/main/res/values folder (se code below). By default the close drawable is a back arrow, but you can change it to the “X” icon like I did below. First add a new Vector Asset, please follow this tutorial to open the Asset Studio, search for the “X” icon (also known as the close icon in the asset studio) and add it.

Finally, modify your MainActivity to look like this

If you run the app now you should see the number of items selected in the ActionMode bar and it should be orange.

Conclusion

In this tutorial, I showed you how to create a RecyclerView with the Staggered Grid Layout and use the RecyclerView Selection library to select multiple items from the RecyclerView widget. You can learn more about the library from the Official Documentation.

You can also find the code on my github. Please ensure to check the “multiple-select” branch where I tried to implement selection from two lists.

--

--