- RecyclerView
- getItemCount()
- onCreateViewHolder
- onBindViewHolder()
- Горизонтальная прокрутка
- Оптимизация
- Android Kotlin Basics – RecyclerView and Adapters
- About This Series
- Check Out the Pluralsight Course!
- RecyclerView and Adapters
- Create a RecyclerView in Your Activity
- Create a CardView and ViewHolder
- Creating an Adapter
- Kotlin Horizontal RecyclerView With CardView Image Android
- Add Gradle Lines
- Model Methods
- Fruit Images
- XML For Child Row
- Adapter For Fruits
- Last Writing
RecyclerView
Компонент RecyclerView появился в Android 5.0 Lollipop и находится в разделе Containers. Для простоты буду называть его списком, хотя на самом деле это универсальный элемент управления с большими возможностями.
Раньше для отображения прокручиваемого списка использовался ListView. Со временем у него обнаружилось множество недостатков, которые было трудно исправить. Тогда решили создать новый элемент с нуля.
Вначале это был сырой продукт, потом его доработали. На данном этапе можно считать, что он стал полноценной заменой устаревшего ListView.
Схематично работу RecyclerView можно представить следующим образом. На экране отображаются видимые элементы списка. Когда при прокрутке списка верхний элемент уходит за пределы экрана и становится невидимым, его содержимое очищается. При этом сам «чистый» элемент помещается вниз экрана и заполняется новыми данными, иными словами переиспользуется, отсюда название Recycle.
Компонент RecyclerView не является родственником ListView и относится к семейству ViewGroup. Он часто используется как замена ListView, но его возможности шире.
Следует сказать, что при работе с ним приходится писать много кода, который пугает новичков. Если с RecyclerView работать не постоянно, то порой забываются детали и сложно вспомнить необходимые шаги. Многие просто сохраняют отдельные шаблоны и копируют в разные проекты.
Внешний вид можно представить не только в виде обычного списка, но и в виде сетки. При необходимости можно быстро переключиться между разными типами отображения.
Для размещения своих дочерних элементов используется специальный менеджер макетов LayoutManager. Он может быть трёх видов.
- LinearLayoutManager — дочерние элементы размещаются вертикально (как в ListView) или горизонтально
- GridLayoutManager — дочерние элементы размещаются в сетке, как в GridView
- StaggeredGridLayoutManager — неравномерная сетка
Можно создать собственный менеджер на основе RecyclerView.LayoutManager.
RecyclerView.ItemDecoration позволяет работать с дочерними элементами: отступы, внешний вид.
ItemAnimator — отвечает за анимацию элементов при добавлении, удалении и других операций.
RecyclerView.Adapter связывает данные с компонентом и отслеживает изменения.
- notifyItemInserted(), notifyItemRemoved(), notifyItemChanged() — методы, отслеживающие добавление, удаление или изменение позиции одного элемента
- notifyItemRangeInserted(), notifyItemRangeRemoved(), notifyItemRangeChanged() — методы, отслеживающие изменение порядка элеметов
Стандартный метод notifyDataSetChanged() поддерживается, но он не приводит к внешнему изменению элементов на экране.
Программисты со стажем знают, что для создания «правильного» ListView нужно было создавать класс ViewHolder. В старых списках его можно было игнорировать. Теперь это стало необходимым условием.
Общая модель работы компонента.
Мы рассмотрим только базовый пример для быстрого знакомства. В реальных проектах примеры будут гораздо сложнее, чтобы обеспечить другие функциональные возможности — обработка жестов, анимация, динамическое удаление и добавление элементов.
Размещаем компонент в макете экрана через панель инструментов. Но сначала добавим зависимость.
Создадим макет для отдельного элемента списка. Варианты могут быть самыми разными — можно использовать один TextView для отображения строк (имена котов), можно использовать связку ImageView и TextView (имена котов и их наглые морды). Мы возьмём для примера две текстовые метки. Создадим новый файл res/layout/recyclerview_item.xml.
Добавим компонент в разметку экрана активности.
Минимальный код для запуска.
Пока ничего сложного, но выводить такой список ничего не будет. Нужен адаптер и данные для отображения. В адаптере описывается способ связи между данными и компонентом.
Начнём по порядку, чтобы запомнить последовательность. Для начала создадим обычный класс и в конструкторе передадим список строк. Список будет содержать имена котов.
Класс MyViewHolder на основе ViewHolder служит для оптимизации ресурсов. Новый класс добавим в состав нашего созданного ранее класса.
В созданном классе нужно просто перечислить используемые компоненты из макета для отдельного элемента списка. В нашем примере задействованы два TextView, инициализируем их через идентификаторы.
Создадим адаптер — наследуем наш класс от класса RecyclerView.Adapter и в качестве параметра указываем созданный нами MyViewHolder. Студия попросит реализовать три метода.
getItemCount()
Как правило данные являются однотипными, например, список или массив строк. Адаптеру нужно знать, сколько элементов нужно предоставить компоненту, чтобы распределить ресурсы и подготовиться к отображению на экране. При работе с коллекциями или массивом мы можем просто вычислить его длину и передать это значение методу адаптера getItemCount(). В простых случаях мы можем записать код в одну строчку.
onCreateViewHolder
В методе onCreateViewHolder нужно указать идентификатор макета для отдельного элемента списка, созданный нами ранее в файле recyclerview_item.xml. А также вернуть наш объект класса ViewHolder.
onBindViewHolder()
В методе адаптера onBindViewHolder() связываем используемые текстовые метки с данными — в одном случае это значения из списка, во втором используется одна и та же строка.
Должно получиться следующее.
Подключаем в активности. Создадим пока бессмысленный список строк, который передадим в адаптер.
Запускаем ещё раз.
Вариант с числами нам не интересен, поэтому добавим котов. Имена котов и кошек разместим в ресурсах в виде массива в файле res/values/strings.xml.
Создадим новую функцию для получения списка котов из ресурсов и передадим его адаптеру.
Горизонтальная прокрутка
Можем указать горизонтальный вариант прокрутки. Остальной код менять не придётся.
А можно вообще обойтись только XML-декларацией.
Оптимизация
При прокрутке под капотом выполняется сложная работа по обновлению контента. Поэтому не следует перегружать элементы списка сложной структурой и не перебарщивайте с вложенными элементами, а также нужно следить за оптимизацией, чтобы избежать лагов.
При работе с изображениями старайтесь использовать готовые библиотеки Picasso, Glide, Fresco и т.д.
Если картинки загружаются с сервера, неплохо заранее вычислять их размеры и пропорции. В некоторых случаях желательно позаботиться, чтобы картинки были одного размера (если это возможно).
Не перегружайте лишним кодом метод onBindViewHolder(). Только самое необходимое.
Источник
Android Kotlin Basics – RecyclerView and Adapters
About This Series
This “Android Kotlin Basics” blog series is all about fundamentals. We’ll take a look at the basics of building Android apps with Kotlin from the SUPER basics, to the standard basics, to the not-so-basics. We’ll also be drawing comparisons to how things are done in Kotlin vs. Java and some other programming languages to build Android apps (like C# and Xamarin or JavaScript/TypeScript for Hybrid implementations).
Check Out the Pluralsight Course!
If you like this series, be sure to check out my course on Pluralsight – Building Android Apps with Kotlin: Getting Started where you can learn more while building your own real-world application in Kotlin along the way. You can also join the conversation and test your knowledge throughout the course with learning checks through each module!
RecyclerView and Adapters
RecyclerViews are the latest way to display a dynamic collection of data in Android and are what have begun to replace the ListView control. This is because of their built in pattern to “recycle” views… the name makes sense. It also allows for more flexibility in layout and display which we will also talk about here.
In order to use a RecyclerView , you need at least the 4 main parts
1. The RecyclerView itself
2. The Adapter to control what data is tied to what view in the recycler.
3. The ViewHolder to control what view is being used within the recycler
4. The LayoutManager to determine how to layout each view in the recycler.
Together, this relationship looks like this:
Meaning the RecyclerView needs it’s two root components set – the LayoutManager and Adapter . The adapter then uses the ViewHolder and appropriate data to manipulate the RecyclerView , and the ViewHolder uses an underlying Layout Resource to inflate the view.
In the end the process looks like this:
Where a user scrolls the list, and as items fall out the top or bottom, they are recycled, cleaned, then re-hydrated with new data from the adapter.
So let’s break down an example of building one of these in Kotlin!
Create a RecyclerView in Your Activity
Let’s first create a simple layout for our MainActivity :
res/layout/activity_main.xml
Then using the Kotlin Android Extensions talked about here: Android Kotlin Basics – Auto-mapping Views we can reference our RecyclerView by its id property.
MainActivity.kt
We’ll come back to this MainActivity once we’ve created our Adapter . But for now we can use the pre-built LinearLayoutManager which will layout the subsequent recycled views Linearly (vertically by default, but it can be set to Horizontal as well).
Create a CardView and ViewHolder
Let’s create the layout resource for our actual article card items, and the ViewHolder to represent it.
res/layout/article_card_item.xml
This is a simple card with an image and title in it that looks something like this:
And with our view, we will need to create a ViewHolder that our Adapter will use to stick data in it:
CardHolder.kt
So here we create a ViewHolder subclass called CardHolder that references its ImageView and TextView that can be initialized right away by querying the passed in itemView property from the constructor. We also add a convenience function to update the ViewHolder and it’s included views with a given WikiPage model (this model is what represents an article from Wikipedia and looks something like this:
WikiPage.kt
WikiThumbnail
This model is the datatype our Adapter will reference as well.
Lastly, I added a quick reference the the Picasso Library from Square in order to load an image from the thumbnail url into our ImageView.
Creating an Adapter
Now the last thing we need to do is connect our ViewHolder and Data to our RecyclerView by creating our Adapter. Here’s what that will look like:
ArticleCardRecyclerAdapter.kt
You can see our ArticleCardRecyclerAdapter inherits from the RecyclerView.Adapter and passes in our CardHolder view holder we just created as the type of ViewHolder . This allows for our required override functions to use that CardHolder as its type.
The adapter requires only 3 functions to be overridden, but there are also other functions available to override.
The three required are:
– getItemCount() to return the number of items the RecyclerView will have within it
– onBindViewHolder() to bind the data of a given position to the CardHolder . Here is where we call that updateWithPage function we created in our CardHolder class.
– onCreateViewHolder() to create the initial view holder by inflating a given layout file (which we use to inflate the article_card_item.xml file.
Now that we have our adapter, we can go and update our MainActivity :
MainActivity.kt
Now you should be able to run and see your list of cards if you’ve loaded a collection of WikiPage models into your currentResults property on the adapter.
Now we can also change the layoutManager property of our recycler to something that might fit our smaller cards a bit better such as the StaggeredGridLayoutManager .
This means we want 2 columns and we want to stack the cards vertically within those columns. If the direction is switched to HORIZONTAL then the number before it will represent the number of rows instead of columns.
Then with that we can have a view like this!
And that’s pretty cool!
Also, let me know what else you’d like to learn about with Android and Kotlin! Either drop a comment here or tweet at me @Suave_Pirate!
If you like what you see, don’t forget to follow me on twitter @Suave_Pirate, check out my GitHub, and subscribe to my blog to learn more mobile developer tips and tricks!
Interested in sponsoring developer content? Message @Suave_Pirate on twitter for details.
Источник
Kotlin Horizontal RecyclerView With CardView Image Android
Read about Kotlin Horizontal RecyclerView With CardView and Image example.
In this tutorial, we will create horizontal recycler view.
Generally, recycler view helps us to show the data in tabular manner and it is vertical mostly.
But sometimes we need to show items horizontally, this is where horizontal recycler view helps us.
There is one in built method in the android system which converts vertical recycler view into the horizontal one.
Let us checkout the below video how horizontal recycler view looks like.
Now follow all the below steps to make a horizontal recycler view.
Add Gradle Lines
Make a new android studio project with “Empty activity” and Kotlin as the source language.
In your new project, open the build.gradle(Module:app) file.
In this file, add the below lines
Android system do not have any built in UI widget to represent Recycler view or Cardview.
So we need to use them externally. For this we should integrate both of them in gradle file.
First line is integrating the Reycler view classes in our project.
Similarly, second line will help us to use the Card view in our project.
Model Methods
Now let us make a class which will work as the data management tool for recycler view.
Make a new Kotlin file and set it’s name as FruitModel.kt
FruitModel.kt should contain the following source snippet
There are two variables in the above file.
One is the string variable (name) and another is integer variable (image_drawable) .
Every Child row of our Recycler view will contain one text view and one image view.
So, string variable (name) set data in text view while integer variable (image_drawable) will preview the image in the image view.
Getter and setter methods in the above file will help us to put values in text view as well as in image view.
Fruit Images
Our recycler view rows are showing one fruit image.
For this, we need to have some sample images in our project.
So click on the below link to download some images of fruits.
After downloading the images, save these fruit images inside the app->res->drawable folder.
XML For Child Row
Go to the app->res->layout directory, and make a new XML file named “recycler_item.xml“
Write down the following source snippet in “recycler_item.xml” file.
Above file will help us to create the look and feel of the each row of recycler view.
You can see that I have added one text view and one image view in the above file.
Both these widgets are under the card view. So it will create card view design.
Adapter For Fruits
Now make a new Kotlin class with name as FruitAdapter.kt
Inside this FruitAdapter.kt class, write the following coding lines
Now in the above file, look at the onCreateViewHolder() method.
This method is inflating the recycler_item.xml file. Thus, it will create layout for each child row using this file.
Now read the onBindViewHolder() method in the above code.
Inside this method, compiler will set the text value in the text view and it will provide image reference in the integer format to the image view.
For this purpose, compiler is using imageModelArrayList as the data source.
We will create this data source in the main activity kotlin file.
Last Writing
Now you should have two main files : MainActivity.kt and activity_main.xml
Inside your activity_main.xml file, write down the following code lines
Main layout of our project is containing just one Recycler view.
Now open your MainActivity.kt file and give it below coding snippet
Now read the following three coding lines
First line is creating an object of the RecyclerView class.
Second line is making an arraylist (imageModelArrayList) which will hold the objects of the FruitModel.kt class.
This arraylist (imageModelArrayList) will work as the data source.
Third line is making an object of the FruitAdapter.kt class.
Now look at the following source codes
There are two variables in the above snippet.
First one is the integer array (myImageList). This myImageList variable holds the reference to the fruit images which we have stored in the drawable folder.
Second variable is the string array (myImageNameList) which have values as the fruit names in the string format.
Now look at the below code of eatFruits() method.
Above method creating our data source. It will create one for loop.
Inside every iteration, compiler will create one object of the FruitModel.kt class and then it will assign the fruit name and “fruit image reference to the drawable folder” to this object.
Then it will add this object to the arraylist called “list“
Now look at the following lines
First line will execute the eatFruits() method and it will fill the data inside the imageModelArrayList which is our data source.
Then compiler will initialize the object of the FruitAdapter class with data source imageModelArrayList.
After this, compiler will set or attach the adapter to the Recycler view.
Last line will convert the traditional vertical recycler view into the Horizontal Recycler View.
Источник