Cardview android studio implementation

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.

Источник

Начало работы с 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 .

Источник

Cardview android studio implementation

Готовый проект будет выглядеть следующим образом: Создадим новый проект в Android Studio. Код для материала был написан в этой IDE, но вы можете воспользоваться любой другой. Для этого примера я выбрал шаблон Scrolling Activity, который хорошо подходит для прокручиваемого содержимого и выполнен в соответствии концепции Material Design. После создания проекта приложение будет выглядеть следующим образом: Сразу скажу, что круглая кнопка в этом материале никак не задействована, но я ее оставил для будущего материала, посвященного работе с JSON, который будет основан на этом материале.

Для работы CardView и RecyclerView нужно добавить библиотеки recyclerview-v7 и cardview-v7 как зависимости. Это можно сделать через меню Android Studio (File – Project Structure – app – Dependencies) или вручную, добавив в файл app/build.gradle следующие строки (для API 26): Еще раз о сути проекта. Мы создаем приложение, которое будет отображать прокручиваемый набор карточек. Для примера данные для карточек будут объектами класса Card с полями title и content. Поэтому создадим в папке с java-исходниками новый файл Card.java. Его содержимое будет следующим: Далее переходим к файлу ScrollingActivity.java, созданному автоматически, после выбора шаблона. Его содержимое (исключая методы: onCreateOptionsMenu() и onOptionsItemSelected()) будет следующим: Переменной rv мы присваиваем ссылку на виджет RecyclerView, который нужно добавить в файл content_scrolling.xml, создаваемый автоматически после выбора шаблона. Разметка виджета следующая: Далее в файле идут следующие строки: Они отвечают за способ размещения представлений в RecyclerView. Все представления будут отображаться в виде списка.

В методе initializeAdapter() создаем адаптер RVAdapter и передаем ему набор карточек. Адаптер заполняет данными компоненты TextView (title и content) для всех карточек. Адаптер будет размещен в одноименном файле RVAdapter.java.

Разметку для карточки разместим в файле cardview.xml (в папке layout). Содержимое файла будет следующим: С разметкой закончили, теперь создадим файл RVAdapter.java. Его содержимое будет следующим: Несколько слов о коде. В методе onCreateViewHolder() создаем новое представление (карточку). В методе onBindViewHolder() заполняем представление данными.

Обработчик нажатий по карточкам
Допустим у вас в активности есть какой-то метод, который нужно запускать при нажатии по отдельной карточке. В этом разделе рассмотрим как это сделать.

Читайте также:  Restart app unity android

Для примера добавим в активность метод, который показывает всплывающее сообщение в Snackbar. В сообщение будем передавать номер карточки по которой нажали.

Итак, добавим в активность новый метод showSnackbar() со следующим содержимым: Далее нужно изменить код в файле RVAdapter.java. Откроем его.

В классе CardViewHolder после строчки CardView cardView; нужно добавить следующие строки: Конструктор CardViewHolder() нужно переписать следующим образом: В методе onCreateViewHolder() нужно изменить строчку возвращаемого значения: Так как мы переписали конструктор CardViewHolder() в коде выше, здесь мы добавляем новый параметр cv.getContext() .

В методе onBindViewHolder() нужно добавить новую строчку для передачи номера нажатой карточки в активность: На этом все. Теперь при нажатии по карточке, в окне приложения, вы будете видеть всплывающее сообщение Snackbar с номером нажатой карточки.

Источник

Android CardView 101: Everything you should know

From card background to compat padding, namespaces to methods

Dec 18, 2017 · 6 min read

If you have been doing layouts for a while now, you must be familiar with the uneasiness that comes with creating layouts, more specifically creating the same layout over and over again for different application components. The general idea for eliminating such a situation is to create a layout template that could be used for multiple components with smaller modifications, which in most of the cases, is the data.

In this post, we will cover a s i milar situation — “How to make cards for different components”. However, instead of discussing the problem, we will be focusing on its solution — CardView. We will assume you have at least basic knowledge of the how-tos of Android development.

CardView was announced by Google during its yearly I/O conference in 2014 as a part of Material Design components. The main purpose CardView serves in the Material Design universe is to provide a unified look to all of the card based UIs making it easier for developers to create seamless interfaces.

In this post, we will see what opportunities CardView provides on Android platform and how to use it properly in our application.

If you look closely to the image on the left, you will notice a white card like view container holding an ImageView, a TextView and an ImageButton. This is our CardView. As I already mentioned, a CardView is a view container or ViewGroup that inherits its nature from FrameLayout which further inherits from ViewGroup itself. The only thing that separates a CardView from any other ViewGroups is its nature to behave like a card, more specifically the shadow and rounded corners. One could argue that such properties can be added to other viewgroups as well, but you will be surprised to know how well CardView behaves on Android versions before Lollipop, something difficult to pull off with custom VGs.

The basic customization that a CardView provides includes CornerRadius, Elevation, MaxElevation, ContentPadding, CompatPadding, PreventCornerOverlap, and a dedicated CardBackgroundColor. The CardView in the image above with all of its customizability enabled can be created using this piece of XML code. Take a look, try to figure out what happens with each of the properties, why is there a ViewGroup inside our CardView viewgroup or simply continue reading to find out.

0. Adding CardView to Project

With the release of Android Lollipop, Google started separating Android Components like RecyclerView and CardView from support library with their own repositories. CardView library can be added to a project by adding the following dependency to dependencies in build.gradle (module: app),

If using Android Studio 3.0 and above, then this needs to be added instead,

1. Why is there a RelativeLayout inside our CardView?

I know I did say a CardView is a ViewGroup but it inherits from FrameLayout which is the simplest form of ViewGroup created to handle a single frame at a time. That’s why we need a RelativeLayout to hold all of our views together while acting like a single frame to the CardView.

2. Card Background Color

The most straightforward property of all. By default, a CardView comes with white card background color which can be modified as per our need to any other color using this property. Sample declaration of cardBackgroundColor (white) in XML and Java looks like this,

3. Card Corner Radius

Card Corner Radius gives the CardView a rounded corner of radius equal to the value provided to it. On Android Lollipop and above, it simply clips the child views that may be intersecting CardView’s rounded corners. It also ensures that a padding is maintained between corners and child views on previous versions to avoid expensive clipping of views. We will soon see how we can enable it. Sample code for 0 corner radius:

Читайте также:  Переводчик для скайпа андроида

4. Card Elevation

Card Elevation property simply elevates the cardview on the z-axis to a height equal to the passed value. Since elevation came with Android Lollipop, Card Elevation on previous versions uses shadows to create a similar effect. It adds padding on its content’s sides using

and on top and bottom using

and then applies shadows to that space. MaxCardElevation property, if not set manually, will be equal to CardElevation. In our example, we have set elevation to 0.7dp and maxElevation to 1dp. If you look at the Java part, you’ll notice the values passed to the methods are different than the values to xml properties. This is because we can specify nature of value with xml but not with java methods which expect the value to be in pixels (px) only and thus we have to pass number of pixels that make up the same dp as xml values.

5. Card Content Padding

As previously mentioned, the normal CardView padding is used to create a space for drawing shadows and thus we use ContentPadding to add padding between the edges and child views. As it’s with normal view padding, ContentPadding can be used to selectively add padding on any of the four edges. In our example, we have used content padding to set padding on all the edges to 10dp and then content padding bottom to 0dp to make sure there is no padding at the bottom. As usual, the Java method needs values for all edges to be passed in pixels. The first parameter of setContentPadding represents left edge, with the last representing bottom.

6. Card Use Compat Padding

One more attribute related to padding. Since CardViews use padding for drawing shadows on platforms before Lollipop, the content area will change on platforms before and after Lollipop. To make sure the content area remains the same on all the platforms, Compat Padding is used which simply adds inner padding on platforms Lollipop and after.

7. Card Prevent Corner Overlap

As mentioned in Corner Radius, the CardView avoids clipping the child views on platforms before Lollipop due to expensive nature of clipping and rather gives an option to distance content from rounded corners with Prevent Corner Overlap. The definition in XML and Java looks like this,

Okay, now that we have discussed about attributes and their method counterparts, let’s see what attribute namespaces we get with CardView. There are actually 2 namespaces that hold the attributes of CardView. The first is the normal android namespace which holds all of the inherited attributes for CardView like width or height or scale. The other one is the app namespace, formerly card and card_view, which holds all the exclusive CardView attributes we discussed just now. It’s often easier to look for special attributes using app namespace.

The complete Java representation of the CardView’s XML layout above looks like this,

The following code does the same as the XML does, same elevation and stuff. The only difference with code is that the methods want the values to be passed in pixels (px) instead of dp or px or mm. This causes a problem on phones with different pixel density and the required value has to be calculated for every device and then converted to px using dpToPx(…) method using device density. Here

will give the same result as

on a Nexus 5 where the pixel density is 3.

That’s it. We now know what a CardView is, what’s the advantage using it, how to correctly use it on different Android versions without making it look different on Lollipop or above and v20 or below. We now also have the idea of different attributes we are supposed to use with a CardView and how they perform on different platforms. Also, knowing the namespaces will help us get better at identifying attributes for our CardView.

If we missed out on any of the CardView features or there’s anything to correct, share it with us in comments below.

Источник

Оцените статью