- Начало работы с RecyclerView и CardView на Android
- Предварительные требования
- 1. Поддержка старых версий
- 2. Создание CardView
- 3. Создание RecyclerView
- Шаг 1. Его определение в макете
- Шаг 2. Использование LayoutManager
- Шаг 3. Определение данных
- Шаг 4. Создание адаптера
- Шаг 5. Использование адаптера
- Шаг 6. Сборка и запуск
- Заключение
- Android Horizontal RecyclerView CardView And Images Example
- Web Host Recommendation
- Look of horizontal Recyclerview
- Step 1. Making Dependencies
- Step 2. Special Layout File
- Downloading Images
- Step 3. Fruit Model
- Step 4. Fruit Adapter
- Looking Heavily At Adapter
- onBindViewHolder() method
- Step 5. Last Modifications
- How does MainActivity.java works ?
- Web Host Recommendation
- Cardview with Recyclerview Android Example [beginners]
- Cardview XML attribute
- Cardview android example with Recyclerview
- Step 1 — Adding dependencies
Начало работы с RecyclerView и CardView на Android
Russian (Pусский) translation by Yuri Yuriev (you can also view the original English article)
Если вам интересно создание приложения для Android, использующего списки для отображения данных, Android Lollipop предлагает два новых виджета, чтобы сделать вашу жизнь проще, RecyclerView и CardView . Эти виджеты приведут внешний вид вашего приложения в соответствие с рекомендациями, указанными в спецификации дизайна Google.
Предварительные требования
Для продолжения используйте последнюю версию Android Studio. Можете взять на Android Developer website.
1. Поддержка старых версий
На момент написания статьи менее 2% Android-устройств работали на Android Lollipop. Однако, благодаря v7 Support Library, вы можете использовать виджеты RecyclerView и CardView на устройствах более ранних версий Android, добавив следующие строки раздела dependencies в файле build.grade вашего проекта:
2. Создание CardView
CardView это ViewGroup . Как любую ViewGroup , её можно добавить в Activity или Fragment через файл XML.
Чтобы создать пустой CardView , вам необходимо добавить следующий код в макет XML:
Для более реалистичного примера давайте создадим LinearLayout и поместим в него CardView . CardView может представлять, например, человека и содержать следующее:
- TextView с именем человека
- TextView с возрастом человека
- ImageView с его фотографией
Так будет выглядеть XML:
Если этот XML будет макетом Activity и в полях TextView и ImageView значимые показатели, так он будет отображаться на устройстве Android:
3. Создание RecyclerView
Шаг 1. Его определение в макете
С экземпляром RecyclerView немного сложнее. Однако определить его в макете XML достаточно просто. Вы можете определить его в макете следующим образом:
Чтобы получить к нему доступ в Activity , возьмите следующий фрагмент:
Если вы уверены, что размер RecyclerView не изменится, можете добавить следующее для повышения производительности:
Шаг 2. Использование LayoutManager
В отличие от ListView , RecyclerView требуется LayoutManager для управления позициями пунктов. Можете определить свой LayoutManager путём расширения RecyclerView.LayoutManager класса. Хотя, можете использовать один из предопределённых подклассов LayoutManager :
- LinearLayoutManager
- GridLayoutManager
- StaggeredGridLayoutManager
В этом уроке я пользуюсь LinearLayoutManager . LayoutManager подкласс, по умолчанию, сделает ваш RecyclerView похожим на ListView .
Шаг 3. Определение данных
Подобно ListView , RecyclerView нужен адаптер для доступа к своим данным. Но прежде, чем мы создадим адаптер, давайте создадим данные, с которыми будем работать. Создайте простой класс для представления лица, а затем напишите метод инициализации объектов List of Person :
Шаг 4. Создание адаптера
Создавая адаптер для RecyclerView , надо расширить RecyclerView.Adapter . Адаптер следует модели view holder , что означает определение пользовательского класса для расширения RecyclerView.ViewHolder . Эта модель минимизирует количество вызовов метода findViewById .
Ранее в этом уроке мы уже определили XML для CardView , который представляет человека. Будем использовать этот макет повторно. Внутри конструктора нашего ViewHolder инициализируйте представления, относящиеся к элементам нашего RecyclerView .
Затем добавьте конструктор в пользовательский адаптер, чтобы он имел доступ к данным, отображаемым RecyclerView . Поскольку наши данные представлены в виде объектов List of Person , используйте следующий код:
RecyclerView.Adapter имеет три абстрактных метода, которые мы должны переопределить. Начнём с метода getItemCount . Это вернёт количество элементов, присутствующих в данных. Поскольку наши данные в List , назначаем метод size на объект List :
Затем переопределите метод onCreateViewHolder . Как следует из названия, этот метод вызывается для инициализации пользовательского ViewHolder . Мы указываем макет, который должен использовать каждый элемент RecyclerView . Это выполняется путем раздувания компоновки с помощью LayoutInflater , передавая результат конструктору ViewHolde r.
Переопределите onBindViewHolder , чтобы указать содержимое каждого элемента RecyclerView . Этот метод похож на метод getView адаптера ListView ‘. В нашем примере, здесь вы должны установить значения имени, возраста и фотографии в CardView .
Наконец, переопределим onAttachedToRecyclerView метод. Сейчас мы можем использовать реализацию этого метода в суперклассе, как показано ниже.
Шаг 5. Использование адаптера
Теперь, когда адаптер готов, добавьте следующий код в Activity , чтобы инициализировать и использовать адаптер, вызывая конструктор адаптера и метод setAdapter в RecyclerView :
Шаг 6. Сборка и запуск
При запуске примера RecyclerView на устройстве Android вы увидите нечто похожее.
Заключение
Из урока вы узнали, как использовать виджеты CardView и RecyclerView , которые были представлены в Android Lollipop. Вы увидели примеры того, как ими пользоваться в приложениях Material Design. Несмотря на то, что RecyclerView может делать почти всё, что может ListView , для небольших наборов данных ListView по-прежнему предпочтительнее, так как требует меньше строк кода.
Для получения дополнительной информации о классах CardView и RecyclerView обратитесь к Android Developers Reference .
Источник
Android Horizontal RecyclerView CardView And Images Example
Android Horizontal RecyclerView CardView And Images Example Tutorial is written here.
Generally, we create vertical recyclerview to show the data in tabular manner.
In this tutorial, we will implement a recyclerview with the horizontal variant instead of vertical.
By default, recyclerview is vertical but android provides a built in method to make recyclerview horizontal.
While we do not have any such method in ListView. So it is easier to make horizontal recyclerview than horizontal listview.
Of course we get same functionality if we make horizontal listview but it is little complex task.
Web Host Recommendation
If you are planning to buy best web hosting at an affordable prize then we recommend bluehost.
(Disclaimer : If you sign up using the above link we may receive small commission without any addition cost to you)
Look of horizontal Recyclerview
If you want to create a horizontal listview then
Follow all the below steps to make horizontal recyclerview.
Step 1. Making Dependencies
To implement recyclerview and cardview, we need to add dependencies separately.
Write the following lines in build.gradle(Module: app)
These lines will fetch required classes to use recyclerview and cardview in your android app.
Step 2. Special Layout File
In recyclerview, we need to create additional layout xml file.
This file will create a view for every single row item. Adapter class will inflate this file while generating the recyclerview row items.
Make a new file res->layout structure. Give it a name as recycler_item.xml
Copy the following source code in recycler_item.xml
As we want to make a cardview, here I have set it in the above file.
Cardview is the parent of all the other views.
Then inside cardview, I have taken one Linearlayout with vertical orientation.
Inside this linearlayout, one imageview and one textview is present. Imageview will be above the textview.
Downloading Images
We will set fruit images in our horizontal recyclerview.
You can download the required fruit images by clicking the below link.
After downloading the images, copy them into the res->drawable directory.
Step 3. Fruit Model
Now let us create a model class. This class is useful to maintain proper data structure.
Create a new class named “FruitModel.java” and add the following code in it.
This class includes the getter ans setter methods for all the UI widgets which are present in the every row of the recyclerview.
In this example, we have one imageview and textview each, so this model have methods for image and text as you can show in the above code.
Step 4. Fruit Adapter
Adapter class will use the data and will create a recyclerview.
Prepare a new class named “FruitAdapter.java”
Write down the below coding lines in “FruitAdapter.java”
Looking Heavily At Adapter
Let us understand the below code
Above is the constructor of FruitAdapter class. It has two parameters.
First parameter will get context and second will get arraylist (imageModelArraList) of the objects of the FruitModel class.
This arraylist imageModelArraList will provide appropriate data to the adapter class.
onBindViewHolder() method
Below is the code for onBindViewHolder() method.
This method will set text in textview and image in the imageview.
It will use that arraylist (imageModelArraList ) to fetch the data.
Compiler will call this method for number of time which is equal to the number of rows in the recyclerview.
Step 5. Last Modifications
Last but not least, make changes in the activity_main.xml and MainActivity.java file.
Copy the following code snippet in activity_main.xml
In the main layout file, I have write only recyclerview code.
Code snippet for MainActivity.java will be as below
How does MainActivity.java works ?
Consider the following source code
Line one is creating an object of the RecyclerView class.
Second line is making an arraylist with the objects of the FruitModel class.
Third will create an object of FruitAdapter class.
Fourth line will create one integer array named myImageList. This myImageList contains as integer reference of the fruit images present in the drawable folder.
Fifth line makes a string array myImageNameList.
myImageNameList holds the names of the fruits.
Attend the following code
Above line is populating an arraylist using the eatFruits method.
Below is the code for eatFruits() methods.
This method will rotate a for loop with seven iterations.
During every iterations, compiler will create an object of the FruitModel class.
Then it will set the image integer reference and image name to that object.
After that compiler will add this object in to the arraylist and this process continues for seven times.
Read the following coding lines
Compiler will create an object of FruitAdapter class with required parameters during first line.
By reading the second line, system will set the adapter with the recyclerview.
Now third line is the most important for us.
It will set the layout to the recyclerview. We are telling compiler to make our recyclerview horizontal in this line.
So, now if you run your project, you should get the output like the video you watched at the starting of the tutorial.
Web Host Recommendation
If you are planning to buy best web hosting at an affordable prize then we recommend bluehost.
(Disclaimer : If you sign up using the above link we may receive small commission without any addition cost to you)
Источник
Cardview with Recyclerview Android Example [beginners]
Cardview Android is a new widget for Android, which can be used to display a card sort of a layout in android. Cardview was introduced in Material Design in API level 21 (Android 5.0 i.e Lollipop).
Since, Cardview is part of material design.It’s such a view which has all material design properties, most importantly showing shadows according to the elevation.
The best part about this view is that it extends FrameLayout and it can be displayed on all the platforms of Android since it’s available through the Support v7 library.
The design of the cardview will be looks like,
In the above picture, every boxes made with cardview in android.
Before jumping into the coding part, Let’s see the Cardview XML attribute, that makes the cardview looks beautiful.
Cardview XML attribute
CardView_cardBackgroundColor : ColorStateList: The new ColorStateList to set for the card background
CardView_cardCornerRadius : float: The radius in pixels of the corners of the rectangle shape
CardView_cardElevation : float: The backward compatible elevation in pixels.
CardView_cardMaxElevation : float: The backward compatible maximum elevation in pixels.
CardView_cardPreventCornerOverlap : boolean: Whether CardView should add extra padding to content to avoid overlaps with the CardView corners.
CardView_cardUseCompatPadding : boolean: true> if CardView should add padding for the shadows on platforms Lollipop and above.
CardView_contentPadding : Sets the padding between the Card’s edges and the children of CardView.
CardView_contentPaddingBottom : int: The bottom padding in pixels
CardView_contentPaddingLeft : int: The left padding in pixels
CardView_contentPaddingRight : int: The right padding in pixels
Done with explanation about the android cardview. Let get into the coding part.
Cardview android example with Recyclerview
In this post, I am going to create cardview with recyclerview in android to list the movies with the image and the movie title.
example application demo,
Step 1 — Adding dependencies
In this example, I am using recyclerview with cardview. But I am not going deeper into recyclerview. I am already have a post on recyclerview in android.
Источник