Posted on

Android RecyclerView With Spinner Sort


android recyclerview spinner sort

Designed by Freepik

Hi, it’s been a while since my last technical post, now I think I’m back. Today we’re going to look at how to create a RecylerView with a Spinner to sort it by different values

First, here’s what Spinner is, lets you select one item from the list

android recyclerview spinner sort

Setup RecyclerView

If you’re not familiar with RecyclerView – check this post first. I’m going to display list of laptops, which are going to have a name and price fields

Next, let’s create a list item to display (list_item.xml)

Those layout, data, variable, @{} come from Data Binding library, a great way to reduce boilerplate code for finding views, improve your layout building speed. In short, to set in up you just need to add those lines to your build.gradle and sync the project

 

Create Holder.java for list items

Again, ListItemBinding comes from Data Binding

Then create Adapter.java for RecyclerView

And finally, initialize RecyclerView in your Activity

binding.list is a reference to your RecyclerView in main_activity.xml

Add Spinner

Now let’s add a Spinner over the RecyclerView

Then set it up in activity

where R.array.sort_types refers to this string-array which I put right into strings.xml

That’s what you’ll get

android recyclerview spinner sort

Sort Items

As you see on the picture above – they aren’t sorted yet, just displayed by insertion order

Let’s set our sorting

In onItemSelected method of OnItemSelectedListener which I set for spinner, there’s a third int argument position, which is position of currently selected spinner item in the string array in order which they are declared (name, price)

And the best thing that onItemSelected method is called on creating activity, so you don’t need to explicitly sort initially, it will be sorted using same item selector listener

Activity onCreate

And just to show where I call all those methods from

 

Very easy, you can get full source code here and check official Spinner documentation if you want