Material card view android

Hands-on with Material Components for Android: Cards

Part 6 of a series covering practical usage of Material Components for Android

This post will be covering the features and API of Card components. To find out how to handle initial setup of Material Components for Android (including the Gradle dependency and creating an app theme), please see my original post:

Setting up a Material Components theme for Android

Attribute by attribute

Cards are sheets of surface material that contain content and actions related to a single subject. This content may include text, images, links and more, and may vary in size. While there are many patterns and variations in terms of content layout, the only required element is the card container.

Basic usage 🏁

A MaterialCardView can be included in your layout like so:

Checking ☑️

A MaterialCardView can be checked to indicate selection. There is no default behavior for enabling/disabling checked state; this can be done in response to long press, for example.

Firstly, checkable behavior needs to be enabled:

We can then toggle checked state (the below example is in response to a long click):

The UI changes include an overlay color and a checked icon:

The checked icon can be changed using the checkedIcon attribute. The various color options will be discussed in the “Theming” section below.

For an advanced checking sample using RecyclerView selection, see the Material Components for Android catalog.

Dragging and swipe-to-dismiss ☝️

MaterialCardView s have built-in support for state changes specific to dragging. As with checking, no default behavior exists to implement the dragging itself. The recommended way of doing this is with ViewDragHelper and the Material Components for Android catalog includes a handy implementation class; DraggableCoordinatorLayout .

Note: It would be useful if DraggableCoordinatorLayout were included in the core Material Components for Android library to allow it to be used without having to copy the class. At the time of writing, the latest release of Material Components for Android is 1.2.0-alpha06 and this is not the case. You can star the feature request for this on the issue tracker.

Firstly, we need to change the parent container to a DraggableCoordinatorLayout :

We can then add a callback and toggle dragged state:

The UI changes include an overlay color and (animated) increased elevation:

For an advanced dragging sample using RecyclerView drag-and-drop, see the Material Components for Android catalog.

Theming 🎨

Cards can be themed in terms of the three Material Theming subsystems: color, typography and shape. When implementing a global card style, extend the Widget.MaterialComponents.CardView style and reference it in your app theme with the materialCardViewStyle attribute.

Читайте также:  Metal slug android apk

Color

The color of the card background can be customized with the cardBackgroundColor attribute. This defaults to colorSurface .

As mentioned above, the foreground color of a card is used to indicate both checked and dragged state. As such, this requires a ColorStateList , meaning a for checked/dragged states is required. It is usually transparent but uses color to indicate checking/dragging, defaulting to colorPrimary (checked)/ colorOnSurface (dragged), with different opacities per state.

The tint color of the checked icon can be customized with the checkedIconTint attribute. This defaults to colorPrimary .

The color of an optional card stroke can be customized with the strokeColor attribute. This is disabled by default.

Lastly, the color of the card touch ripple can be customized with the rippleColor attribute. It too accepts a ColorStateList and defaults to colorOnSurface (unchecked)/ colorPrimary (checked), with different opacities per state.

Typography

There is no primary text as part of card components. Text included in the contents of a card will be styled according to the class/component used as well as the fontFamily app theme attribute.

Shape

The shape of a card background can be customized with the shapeAppearance attribute. This defaults to shapeAppearanceMediumComponent .

The elevation of a card can be customized with the cardElevation attribute. This defaults to 1dp.

Interestingly, the corner size of a card’s current shape appearance can be interpolated between 0.0 and 1.0. This can be useful in animations and transitions. Use MaterialCardView#setProgress and MaterialCardView#getProgress for this.

While not strictly shape theming, it is worth mentioning that the width of an optional card stroke can be adjusted with the strokeWidth attribute. This defaults to 0dp (and will not be rendered if no strokeColor is set, regardless of width).

Источник

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.

Источник

Material 2.0 для разработчиков. Краткий обзор новых компонентов

В мае на Google I/O мы впервые увидели Material Design 2.0. Команда Google провела крупный рефакторинг и выпустила обновленную библиотеку дизайна. В ней появились новые компоненты и анимации. Мы следим за развитием Material Components с самого начала. Сейчас все находится на стадии RC1, и уже скоро выйдет в релиз. Под катом обзор новых и обновленных UI-компонентов для тех, кто еще не пробовал их в работе, но интересуется.

Android X вместо Support library

«Как это уже задеприкейтили? Я даже попробовать ее толком не успел», – сказал один мой знакомый, когда узнал о переезде Material Components в новый пакет. Действительно, поддержки support.design больше не будет, а на ее место придет com.google.android.material.
В рамках проекта Android X Google устроили рефакторинг всей библиотеки поддержки и архитектурных компонентов. Подробнее можно почитать в их блоге. Вот пример некоторых пакетов:

старый пакет

новый пакет

androidx.@
androidx.databinding.@
com.google.android.material.@

К счастью, для «мягкого» переезда на новую библиотеку, в студии появится инструмент, позволяющий автоматически обновить все зависимости. Сейчас это доступно уже в Android Studio Canary 3.3. Он призван автоматически находить все зависимости в импортах, в gradle файлах, в XML и в Proguard.

Material library

Все старые UI-компоненты из Support Library переехали в Material library, а ещё появились новые компоненты. Добавим в проект новую зависимость:

Обратной совместимости с Support не предполагается. Придется избавиться от всех остальных зависимостей, где встречается слово support, и заменить их на соответствующие из Android X. Иначе проект просто не соберется из-за множества конфликтов. Для тестовой сборки мне пришлось даже заменить Glide на Picasso, потому что первый тянет за собой android-support. На большом проекте вручную это делать будет неудобно.

Однако для тестирования Material Components можем воспользоваться support:design версии 28-beta, куда Google любезно продублировала все актуальные компоненты. Несмотря на это, 28 версия Support library будет последней, и в дальнейшем ее поддержка прекратится. А теперь давайте посмотрим на новые компоненты, и измененные старые.

BottomAppbar

BottomAppbar – это что-то похожее на Appbar, только с возможностью прикрепления Floating Action Button и вырезом под него. Предназначен для работы внутри CoordinatorLayout.
Вот некоторые параметры, которые мы можем кастомизировать:

  • app:backgroundTint — цвет заполненного пространства
  • app:fabAlignmentMode — положение FAB
  • app:fabCradleMargin — отступ между FAB и BottomAppbar
  • app:fabCradleRoundedCornerRadius — закругление на углах выреза для FAB
  • app:fabCradleVerticalOffset
  • app:hideOnScroll

На момент написания статьи, BottomAppBar доделан не до конца. Например, нельзя разместить NavigationIcon в центре по вертикали, но, наверное, это скоро допилят.

Chips

Chip – еще одна новая View в библиотеке. С её помощью можно удобно показывать перечисление небольших объектов. Например, фильтры или какие-нибудь подсказки для пользователя. По гайдлайнам Chip обладает следующими свойствами:

  • Может иметь иконку контента (слева).
  • Может иметь иконку для удаления (справа).
  • Содержит текст.
  • Может находится в двух состояниях, как CheckBox.
Читайте также:  Не установился драйвер android

Реализация в Material library представляет из себя расширенную версию AppCompatCheckBox, и может порадовать нас такими кастомизируемыми параметрами:

  • app:chipCornerRadius
  • app:chipMinHeight
  • app:chipBackgroundColor
  • app:chipStrokeColor
  • app:chipStrokeWidth
  • app:rippleColor
  • android:text
  • android:textAppearance
  • app:chipIconVisible
  • app:chipIcon
  • app:chipIconTint
  • app:chipIconSize
  • app:closeIconVisible
  • app:closeIcon
  • app:closeIconSize
  • app:closeIconTint
  • app:checkable
  • app:checkedIconVisible
  • app:checkedIcon
  • app:showMotionSpec
  • app:hideMotionSpec

Приятно удивило наличие ChipGroup, являющегося наследником FlexboxLayout, которого наконец-то включили в библиотеку дизайна.

BackDrop

BackDrop – новый для Android паттерн навигации. Есть основной контент, который расположен на переднем плане, и дополнительная область, лежащая позади (обычно это меню навигации). Если нужно добраться до контента сзади, то передний план съезжает вниз до нужного уровня.
Состоит Backdrop из трех элементов:

На момент написания статьи он еще не реализован в библиотеке, и в соответствующем репозитории пока пусто. Поэтому пришлось делать свою реализацию, обернув ее в библиотеку:

Просто прикрепляем BackdropBehavior на нужный Front Container и передаем ему Toolbar и Back Container.

XML

Kotlin

Это просто один из вариантов реализации. Но для моего кейса получилось удобно. Думаю, решение Google будет несколько отличаться. Если вдруг есть предложения, то с радостью готов обсудить их в комментариях под статьей.

MaterialButtons

MaterialButtons – обновленные более кастомизируемые кнопки. У них есть следующие параметры для кастомизации:

  • android:inset (Left, Top, Right, Bottom) — отступ кнопки от края View
  • app:backgroundTint — цвет заполнения кнопки
  • app:backgroundTintMode
  • app:icon — можно добавить иконку, по умолчанию слева от текста
  • app:iconPadding
  • app:iconTint
  • app:iconTintMode
  • app:strokeColor — для создания кнопок с обводкой
  • app:strokeWidth
  • app:cornerRadius
  • app:rippleColor

Конечно, эти стили для кнопок всегда можно сделать самостоятельно. Но теперь кастомизация кнопок хорошо работает «из коробки», и это очень удобно.

Например, чтобы сделать кнопку с крестиком, раньше пришлось бы писать два XML файла:

Layout:

bg_button.xml

Теперь описать кнопку можно сразу на месте:

Text Fields

Text Fields – тоже претерпел изменения. Теперь текстовому полю «из коробки» можно добавить обводку по контуру, сделать его залитым каким-то цветом, или закруглить отдельные углы.

Как и раньше, можно использовать конструкцию из InputLayout с дочерним EditText, для более удобного для отображения подсказок, ошибок и прочего выделения текста.

  • app:boxCornerRadiusTopLeft
  • app:boxCornerRadiusTopRight
  • app:boxCornerRadiusBottomLeft
  • app:boxCornerRadiusBottomRight
  • android:hint
  • app:hintEnabled
  • app:errorEnabled
  • app:setError
  • app:helperTextEnabled
  • app:helperText
  • app:passwordToggleEnabled
  • app:passwordToggleDrawable
  • app:counterEnabled
  • app:counterMaxLength

Изменения тоже не очень существенные, но кастомные решения можно разрабатывать теперь намного быстрее. С точки зрения бизнеса, скорость разработки имеет значение, и тут Google постарались неплохо.

MaterialCardView

MaterialCardView – это все старая CardView, но теперь с обводкой по контуру, как у кнопок.

Итого

Существенных изменений не так много. Новые механизмы кастомизации просто позволяют сделать чуточку проще то, что мы все делали и раньше. Зато появилась проблема совместимости с Support library. Разработчикам библиотек придется переезжать на Android X, что отнимет много времени и нервов. Особенно, если учесть, какая кодовая база сейчас support-ориентированна. Несмотря на то, что Google предоставляет инструмент для автоматизации переезда с заменой всех импортов, работает он не идеально. Подобные переезды на своих проектах все-таки придется пережить с некоторыми трудностями.

На данный момент не все заявленные Material-компоненты реализованы корректно, а некоторые не реализованы совсем. Будем смотреть, будем пробовать.

Источник

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