- Kotlin Android RecyclerView : How to Sort Data – Examples
- Data Sorting
- RecyclerView
- Example 1: Kotlin Android – RecyclerView Sort Ascending/Descending
- Our Video tutorial
- Let’s look at Code
- 1. Gradle Scripts
- 2. Layouts
- 3. Kotlin Code
- Download
- Learn Android Retrofit
- Example 2: Android RecyclerView – Sort Ascending/Descending
- Screenshot
- Common Questions this example explores
- Tools Used
- Libaries Used
- Source Code
- Build.Gradle
- MyViewHolder.java
- MyAdapter.java
- MainActivity.java
- ActivityMain.xml
- ContentMain.xml
- Model.xml
- Video/Preview
- Download
- How To Run
- Android SortedList – Sort Multiple Data Types recyclerView
- Introduction to SortedList
- Example – RecyclerView Sort based on different types/field using SortedList
- Video Tutorial
- Gradle Scripts
- Layouts
- Our Classes
- Resources
- YouTube
- Работа с RecyclerView в Andriod (Kotlin)
- Что такое RecyclerView?
- Начало
- Кастомный ViewHolders
- Инициализация RecyclerView в нашем Fragment и присвоение данных списку.
Kotlin Android RecyclerView : How to Sort Data – Examples
In a previous lesson we had looked at how to sort data but with simpler adapterviews like listview, gridview and spinner. In this tutorial you will learn how to sort data while working with recyclerview.
But first let’s introduce some terms.
Data Sorting
Generally data sorting refers to the process of arranging data in a particular manner for several uses. These uses include ease of analysis and efficiency. Sorted data are easier to read and analyze which is good for us humans. However they are also good for computers as it makes processing of data much more efficient. The main reason for these is that we or the computers can ignore some data and jump to specific location.
It’s why for example binary search is much faster and efficient than many other searches including linear searching. This is because that algorithm involves splitting data into two and ignoring one half. On the other hand with linear search the data is normally not sorted hence you have to search against all items.
Imagine if in your contacts application in your mobile device, if the contacts were not sorted. If you wanted to find a given contact, yet the contact was listed the last in the list, you would have to scroll through all contacts. You would be checking the contacts one by one. However for sorted data that is easy as you simply scroll to the appropriate letter. For example, if the contact’s name is Zak, then you would certainly scroll to the last item directly.
RecyclerView
RecyclerView is a list component that allows us render large data sets efficiently. These days it is the most commonly used adapterview. This courtesy of it’s felxibility, power and ease of use. Like other adapterviews, recyclerviews need adapter. It is the adapter that maintains the data source on behalf of recyclerview.
Given the large use scenarios of recyclerviews, it makes sense to be able to sort them.
Example 1: Kotlin Android – RecyclerView Sort Ascending/Descending
This is an android tutorial of how to sort in both ascending and descending manner in recyclerview using Kotlin programming language.
You click a button to toggle between ascending and descending manner.
Our Video tutorial
Have a look at our video tutorial here:
Let’s look at Code
1. Gradle Scripts
(a). build.gradle(app)
This is our app level build.gradle.
Our programming language is Kotlin hence we will apply the kotlin-android plugin, alongside the com.android.application plugin.
We will also add the design support as well as the cardview under the dependencies DSL.
We’ve added the appcompat, cardview and design support libraries. Recyclerview is contained in the design support.
2. Layouts
(a). activity_main.xml
We have a button on top of a recyclerview. The recyclerview will display our data.
When the button is clicked, we toggle the sort between ascending and descending manner.
We wrap these two widgets in a relativelayout.
You can see you declare recyclerview using the android.support.v7.widget.RecyclerView class. Then we’ve assigned it an id which will be used to identify it.
(b). model.xml
At the root view of this layout we have a cardview.
Our CardView will have only a simple textview.
3. Kotlin Code
(a). MainActivity.kt
Then we have our MainActivity. The class obviously derives from appcompatactivity.
We’ve started by declaring several variables as instance fields. The y include:
- Button – Will be clicked so as to sort.
- RecyclerView – Will render our data.
- Adapter – Our recyclerview adapter.
- Boolean – Will allow us to maintain the status of the sort. For example true means the data is the sorted in ascending while false means the data is either unsorted or sorted in descendng manner.
(b). MyAdapter.kt
Here’s our adapter class.
Because we use a recyclerview, our adapter is RecyclerView.Adapter with VH being our ViewHolder class.
Download
You can download full source code below.
No. | Location | Link |
---|---|---|
1. | GitHub | Direct Download |
2. | GitHub | Browse |
Learn Android Retrofit
Example 2: Android RecyclerView – Sort Ascending/Descending
RecyclerView is one of those views that you wouldn’t believe haven’t been in android for a long time. It’s so popular and heavily used since it’s introduction in API level 22.
RecyclerView class resides in android.view.ViewGroup. Android describes it as a flexible view for providing a limited window into a large dataset. Well for us, we are interested in this dataset: how to sort it.
Sorting data is important especially in components like recyclerview wihich can display massive amounts of data. No user would like the problem of having to read through each of the list of items just to find a specific data. he can simply sort and reach it quicker.
This example uses Collections API to sort data in ascending and descending order.User clicks sort button to toggle between sorting ascending and descending. You can find more details about WebView here.
Screenshot
- Here’s the screenshot of the project.
Android RecyclerView Sort Example
Common Questions this example explores
- How to sort data in RecyclerView.
- Sorting Collections in android java.
- RecyclerView with CardViews. Sort CardViews
- Sort RecyclerView in ascending and descending manner.
Tools Used
This example was written with the following tools:
- OS: Windows 8.1
- IDE : AndroidStudio
- Emulator : Genymotion
- Language : Java
Libaries Used
- No third party library was used in this project.
Source Code
Lets jump directly to the source code.
Build.Gradle
- Normally in android projects, there are two build.gradle files. One is the app level build.gradle, the other is project level build.gradle. The app level belongs inside the app folder and its where we normally add our dependencies and specify the compile and target sdks.
- Also Add dependencies for AppCompat and Design support libraries.
- Our MainActivity shall derive from AppCompatActivity while we shall also use Floating action button from design support libraries.
MyViewHolder.java
- Our ViewHolder class.
- Derives from RecyclerView.ViewHolder.
- Holds our view for Recycling.
MyAdapter.java
- Our Adapter class.
- Derives from RecyclerView.ViewHolder.
- Inflates our model layout into RecyclerView ViewItems.
- Adapts our data to RecyclerView ViewItems.
MainActivity.java
- Launcher activity.
- Derives from AppCompatActivity.
- ActivityMain.xml inflated as the contentview for this activity.
- We initialize views and widgets inside this activity.
- We fill an arraylist,sort it, pass it to our adapter and set that adapter to our RecyclerView.
ActivityMain.xml
- Template layout.
- Contains our ContentMain.xml.
- Also defines the appbarlayout, toolbar as well as floatingaction buttton.
ContentMain.xml
- Content Layout.
- Defines the views and widgets to be displayed inside the MainActivity.
- In this case its a simple webview.
Model.xml
- ViewItem Layout.
- Root layout is CardView.
- Defines the views and widgets to be inflated as our viewitems.
- In this case its a cardview with textview.
Video/Preview
- Video version of this tutorial. Coming soon…
Download
How To Run
- Download the project above.
- You’ll get a zipped file,extract it.
- Open the Android Studio.
- Now close, already open project.
- From the Menu bar click on File >New> Import Project.
- Now Choose a Destination Folder, from where you want to import project.
- Choose an Android Project.
- Now Click on “OK“.
- Done, your done importing the project,now edit it.
Android SortedList – Sort Multiple Data Types recyclerView
Introduction to SortedList
Android SDK provides a class called SortedList that provides us an easy way to sort data. SortedList is able to respect the order of items added to it and notify of changes to that order.
It was added in android version 22.1.0 and belongs to the android.support.v7.util package. As a class it’s concrete and only extends the java.lang.Object class:
To order items it uses the compare(Object,Object) method. That method uses binary search to fetch the items to be ordered.
The order of items and change notifications can be controlled via the SortedList.Callback parameter.
SortedList has two inner classes:
No. | Class | Function |
---|---|---|
1. | SortedList.Callback | A callback implementation that can batch notify events dispatched by the SortedList. |
2. | SortedList.BatchedCallback | The class that controls the behavior of the SortedList. |
Example – RecyclerView Sort based on different types/field using SortedList
Let’s come create an example to allow us sort a recyclerview based on different fields. The app will list stars. Each star will have a name, comments, favorites and views. Users can then sort for based on number of comments, favorites, view count and name. They can do it both in ascending and descending manner of the above properties.
Video Tutorial
Watch the video tutorial below for more details.Please remember to like and subscribe.
Gradle Scripts
Start by adding the following dependencies in your app level build.gradle file:
You can see there is no special library or dependency we are using, just common androidx components.
Layouts
We will have three layoust:
No. | Layout | Role |
---|---|---|
1. | activity_main.xml | Is our main activity’s layout. |
2. | model.xml | Will be inflated into our recyclerview items when sorting in ascending manner. |
3. | model_grid.xml | Will be inflated into our recyclerview items when sorting in descending manner. |
(a). activity_main.xml
In your activity_main.xml file add the following code:
You can see we have the following components used above:
- RecyclerView – To render our data.
- Buttons – To sort in ascending/descending manner.
- Spinner – To choose the field to sort with e.g comments,views,favorites.
(b). model.xml
To model a single item to be rendered as part of the list of items in our recyclerview. Will be inflated when we are using LinearLayouManager.
(c). model_grid.xml
To model a single item to be rendered as part of the list of items in our recyclerview. Will be inflated when we are using GridLayoutManager.
Our Classes
Start by creating the following three classes:
- Star.java
- MainActivity.java
- SortedListAdapter.java
(a). Star.java
This class will represent our data object. We will be showing lists of stars in our recyclerview.
Make sure you have our Star class:
In the Star class add the following:
You can see in the above we have defined one string and three integers. Those will be the properties of our Star object. We will sort based on those properties.
We have also created a constructor to receive those properties.
Then add our gettes and setters:
(b). SortedListAdapter.java
Make the SortedListAdapter class extend the RecyclerView.Adapter class:
Then add the following:
You can see we’ve defined a SortedList class to contain our stars. Then an integer to hold the layout we will be inflating.
The constructor is receiving the layout and assigning it to the local variable. Then we are invoking a method known as sort(), well we wil be defining that method shortly.
Let’s go ahead and define that sort method:
You can see it’s receiving two parameters:
- boolean value – The sort direction(ascending/descending)
- property – Property or field to sort.
You can also we have overrided a couple of methods that allow us react to changes to our sort order.
We will then create a method to add data to our SortedList:
We also have methods to get as well clear that SortedList:
FULL CODE: SortedListAdapter.java
(c). MainActivity.java
Finally we can put everything together in our MainActivity class:
Resources
No. | Site | Action |
---|---|---|
1. | Github | Browse |
2. | Github | Download |
3. | YouTube | Watch |
4. | Android Documentation | Reference |
YouTube
- Visit our channel for more examples like these.
- Lets share tips and ideas in our Facebook Page.
report this ad
Источник
Работа с RecyclerView в Andriod (Kotlin)
glabrion 28 октября, 2019
Что такое RecyclerView?
RecyclerView по существу является ViewGroup с контейнерами называемыми ViewHolders, которые содержат особые элементы (item). RecyclerView это большой Android класс обеспечивающий гибкий UI (пользовательский интерфейс). Огромная польза использования RecyclerView состоит в том, что Вы способны эффективно переиспользовать view. Вы не создаете все элементы списка, а храните с памяти элементы видимые на экране.
Для RecyclerView необходимо:
- массив данных
- адаптер — для привязки этих данных
- xml файл отображения отдельного элемента view
- ViewHolder для отображения данных из xml-файла.
Итак, мы познакомились с RecyclerView и с его основными компонентами. Давайте создадим свой список RecyclerView.
Начало
Мы собираемся сделать список RecyclerView . В элементе списка будет название фильма и год его выпуска. В разметке нашего фрагмента добавим элемент android.support.v7.widget.RecyclerView. В этом месте будет отображаться наш список.
Добавим так же в отдельный файл разметку:
Эта разметка будет отображать вид одного элемента в списке. Как мы видим элемент списка будет отображать два текстовых поля.
Мы создаем data класс. В этом классе будет информация и фильме и дате выпуска.
Кастомный ViewHolders
Далее создадим класс MovieViewHolder (экземпляр этого класса по сути является элементом в списке), и создадим кастомный Adapter который будет связывать наши MovieViewHolders в RecyclerView.
Класс MovieViewHolder будет наследоваться от класса RecyclerView.ViewHolder
Наш ListAdapter мы наследуем от RecyclerView.Adapter (). Нам надо переопределить три метода: onCreateViewHolder(…) , onBindViewHolder(…) , и getItemCount() .
- getItemCount() возвращает общее количество элементов списка. Значения списка передаются с помощью конструктора.
- onCreateViewHolder() создает новый объект ViewHolder всякий раз, когда RecyclerView нуждается в этом. Это тот момент, когда создаётся layout строки списка, передается объекту ViewHolder, и каждый дочерний view -компонент может быть найден и сохранен.
- onBindViewHolder() принимает объект ViewHolder и устанавливает необходимые данные для соответствующей строки во view -компоненте.
Инициализация RecyclerView в нашем Fragment и присвоение данных списку.
Во фрагменте мы должны присвоить списку layoutManager. Это то как мы хотим чтобы отображался список (сетка, элементы следуют один за другим и др.)
Источник