- Using the CardView
- Ripple Effect on androidx.cardview.widget.CardView
- 3 Answers 3
- Ripple effect on Android Lollipop CardView
- 14 Answers 14
- Русские Блоги
- Свойства Android CardView и обзор использования
- Использование CardView:
- Введение в атрибут CardView:
- Ниже мы сначала рассмотрим эффект Ripple CardView (более 5.0, включая Android5.0) на нескольких конкретных примерах:
- Из рисунка 3: Пока свойство переднего плана не установлено, эффект Ripple не будет отображаться: на рисунках 4 и 5 показаны версии системы Android5.0 и более поздние с собственным установленным в системе эффектом щелчка; на рисунке 6 показана версия Android5.0 и более поздние Настроены передний план для достижения эффекта Ripple: на рисунках 7 и 8 показаны Android 5.0 и ниже, использующие собственный эффект щелчка системы и пользовательский передний план для достижения эффекта Ripple, фактически можно увидеть, что ниже эффекта Android 5.0 нет эффекта Ripple.
- Если вы прямо установите свойство Android: background = «@ drawable / item_selector» в CardView, оно не будет действовать. Вы можете установить эффект пульсации щелчка CardView, установив атрибут android: foreground = «» в CardView. Вы можете выбрать эффект щелчка, который поставляется с системой, или вы можете настроить его для достижения желаемого эффекта щелчка
- Настраиваемый эффект CardView click Ripple
- CardView затенение по оси Z
- Филе покрытия
- lift-on-touch
- Сводка CardView
Using the CardView
Android 7.0 introduces a new widget called CardView which essentially can be thought of as a FrameLayout with rounded corners and shadow based on its elevation. Note that a CardView wraps a layout and will often be the container used in a layout for each item within a ListView or RecyclerView.
CardView should be used when displaying heterogeneous content (where different cards show different types of information). Using a list or a grid of tiles (non-cards) for homogeneous content is preferred since the boundaries in a card can distract the user from quickly scanning a list.
Lets assume your layout looks something like this:
To create a card using this layout, first you need to import the CardView from AndroidX library in your build.gradle file.
Now replace the FrameLayout with CardView .
CardView provides a default elevation and corner radius so that cards have a consistent appearance across the platforms. However, you may choose to customize these values if you desire to do so. We can also set the background color of the card.
Note that the card_view:cardElevation is used to determine the size and softness of the shadow so as to realistically depict the depth. These properties can be set programmatically as well:
See the CardView docs for additional properties.
By default, a CardView is not tappable and it doesn’t show any touch feedback. Touch feedback animations provide users with visual feedback when a CardView is touched. To enable this behavior, add the following attributes to your CardView .
Using the android:foreground=»?android:attr/selectableItemBackground» property on a CardView enables the ripple effect to originate from the touch origin.
On platforms before Android L, CardView adds padding to support corner radius, since rounded corner clipping can be an expensive operation. Similarly, for shadows, before L, CardView adds content padding and draws shadows to that area. This content padding is based on the elevation, and as per the docs:
This padding amount is equal to maxCardElevation + (1 — cos45) * cornerRadius on the sides and maxCardElevation * 1.5 + (1 — cos45) * cornerRadius on top and bottom.
Thus, if you would like to specify custom padding on the content, you need to use a new attribute card_view:contentPadding .
Similarly, to change the background color of a CardView, you need to use a new attribute card_view:cardBackgroundColor .
Источник
Ripple Effect on androidx.cardview.widget.CardView
I am trying to add ripple effect on click of card view strangely it is not coming up?
What could be wrong here?
// I have a linear layout with three textview inside the cardview.
3 Answers 3
Don’t use any background/foreground in CardView . If you use any background color then, then just add app:cardBackgroundColor=»@color/cardBackgroundColor . Remove any padding from the CardView . Use margin for space between items.
Now, for the ripple effect in CardView , just add an immediate child layout in your CardView . Set android:background=»?attr/selectableItemBackground» in the child layout. Add any necessary padding/margin in the child if you need.
Please use com.google.android.material.card.MaterialCardView in favor of androidx.cardview.widget.CardView that will give that function out of the box.
Background: https://developer.android.com/jetpack/androidx/releases/cardview is the new base superseding https://developer.android.com/topic/libraries/support-library/packages#v7-cardview and Material Components https://developer.android.com/reference#other-libraries are build on top of androidx.cardview using foreground and rippleColor as defined per https://material.io/components/cards/android#card anatomy . so check out if you customize your ?attr/colorSurface , ?attr/colorOnSurface or app:cardForegroundColor to set matching values each other for a visible change
Existing CardView does not having ripple effect, use MaterialCardView it has ripple effect.
here is the sample code for MaterialCardView
Источник
Ripple effect on Android Lollipop CardView
I’m trying to get a CardView to display the ripple effect when touched by setting the android:backgound attribute in the activity XML file as described here on the Android Developers page, but it isn’t working. No animation at all, but the method in onClick is called. I’ve also tried creating a ripple.xml file as suggested here, but same result.
The CardView as it appears in the activity’s XML file:
I’m relatively new to android development, so I might have made a few obvious mistakes.
14 Answers 14
You should add following to CardView :
Add these two line code into your xml view to give ripple effect on your cardView.
I managed to get the ripple effect on the cardview by :
and for the custom_bg that you can see in above code, you have to define a xml file for both lollipop(in drawable-v21 package) and pre-lollipop(in drawable package) devices. for custom_bg in drawable-v21 package the code is:
for custom_bg in the drawable package, code is:
so on pre-lollipop devices you will have a solid click effect and on lollipop devices you will have a ripple effect on the cardview.
The ripple effect was omitted in the appcompat support library which is what you’re using. If you want to see the ripple use the Android L version and test it on an Android L device. Per the AppCompat v7 site:
«Why are there no ripples on pre-Lollipop? A lot of what allows RippleDrawable to run smoothly is Android 5.0’s new RenderThread. To optimize for performance on previous versions of Android, we’ve left RippleDrawable out for now.»
Check out this link here for more info
If the app minSdkVersion which you are working is level 9, you can use:
Instead, starting from level 11, you use:
clickable — Defines whether this view reacts to click events. Must be a boolean value, either «true» or «false».
foreground — Defines the drawable to draw over the content. This can be used as an overlay. The foreground drawable participates in the padding of the content if the gravity is set to fill.
Use Material Cardview instead, it extends Cardview and provides multiple new features including default clickable effect :
Dependency (It can be used up to API 14 to support older device):
For me, adding the foreground to CardView didn’t work (reason unknown :/)
Adding the same to it’s child layout did the trick.
CODE:
Add these two like of code work like a charm for any view like Button, Linear Layout, or CardView Just put these two lines and see the magic.
If there is a root layout like RelativeLayout or LinearLayout which contain all of the adapter item’s component in CardView, you have to set background attribute in that root layout. like:
For those searching for a solution to the issue of the ripple effect not working on a programmatically created CardView (or in my case custom view which extends CardView) being shown in a RecyclerView, the following worked for me. Basically declaring the XML attributes mentioned in the other answers declaratively in the XML layout file doesn’t seem to work for a programmatically created CardView, or one created from a custom layout (even if root view is CardView or merge element is used), so they have to be set programmatically like so:
Where MadeupCardView extends CardView Kudos to this answer for the TypedArray part.
Источник
Русские Блоги
Свойства Android CardView и обзор использования
Использование CardView:
Если вы не знаете версию карты, на которую хотите положиться, вы можете добавить зависимости, выполнив следующие действия:
1. Наведите курсор мыши на модуль, который нужно добавить, щелкните правой кнопкой мыши и выберите «Открыть настройки модуля», как показано на рисунке 1:
2. Согласно рисунку 2 в настройках модуля:
Нажмите OK и дождитесь завершения строительства.
Введение в атрибут CardView:
Google официально интерпретирует предложение CardView: FrameLayout с теневым фоном и закругленными углами.
Вот некоторые общие свойства CardView:
Ниже мы сначала рассмотрим эффект Ripple CardView (более 5.0, включая Android5.0) на нескольких конкретных примерах:
Из рисунка 3: Пока свойство переднего плана не установлено, эффект Ripple не будет отображаться: на рисунках 4 и 5 показаны версии системы Android5.0 и более поздние с собственным установленным в системе эффектом щелчка; на рисунке 6 показана версия Android5.0 и более поздние Настроены передний план для достижения эффекта Ripple: на рисунках 7 и 8 показаны Android 5.0 и ниже, использующие собственный эффект щелчка системы и пользовательский передний план для достижения эффекта Ripple, фактически можно увидеть, что ниже эффекта Android 5.0 нет эффекта Ripple.
Коды клавиш части макета следующие:
Если вы прямо установите свойство Android: background = «@ drawable / item_selector» в CardView, оно не будет действовать. Вы можете установить эффект пульсации щелчка CardView, установив атрибут android: foreground = «» в CardView. Вы можете выбрать эффект щелчка, который поставляется с системой, или вы можете настроить его для достижения желаемого эффекта щелчка
Существует два варианта собственных эффектов системы:
1、android:background=»?android:attr/selectableItemBackground»Рябь имеет границу
2、android:background=»?android:attr/selectableItemBackgroundBorderless»Рябь за границей
Второй метод должен указать версию Android5.0, то есть tools: targetApi = «lollipop» в приведенном выше файле макета.
После этой настройки на устройствах с Android 5.0 и выше появляется эффект ряби, и ниже Android 5.0 нет пульсаций, меняется только цвет переднего плана.
Настраиваемый эффект CardView click Ripple
Нужно разделить на две ситуации: Android5.0 и выше и Android5.0 ниже
Android 5.0 (версия V21) и выше можно напрямую настроить с помощью Ripple. Эффект показан на рисунке 6. Существует еще много способов использования Ripple в Интернете, и здесь больше нет введения:
Ниже Android5.0, просто используйте селектор, чтобы установить его. На самом деле, он только меняет цвет переднего плана, и эффект Ripple отсутствует. Эффект показан на рисунке 8:
CardView затенение по оси Z
Google представил тени (высота) и смещение оси Z в Material Design после Android 5.0. При использовании CardView в младших версиях (до Android5.0) система добавит совместимость Elevation с CardView (то есть app: cardElevation в XML и setCardElevation в коде Java), что также приводит к разнице между Android5.0 CardView имеет разные размеры в системе.
Чтобы решить эту проблему, есть два метода:
1. Используйте свойство setUseCompatPadding и установите для него значение true (значение по умолчанию — false), чтобы CardView мог использовать одно и то же значение заполнения в разных системах;
2. Адаптация ресурсов измерений с использованием разных версий API (то есть с помощью разных файлов dimension.xml в папках values и values-21):
- Создайте папки ресурсов / res / value и / res / value-v21 в каталоге Module, соответствующем проекту. В первом размещаются файлы старой версии / универсальных ресурсов (вы можете пропустить его, если знаете), а во втором размещаются ресурсы SDK версии 21 и новее. файл.
- Создайте измерение (атрибут ) в измерении. В качестве значения введите имя (например, xxx_card_margin) и введите значение 0dp.
- Затем создайте Dimension с тем же именем в Dimen.xml в папке value-v21 и заполните желаемое поле (как правило, того же размера, что и тень CardElevation)
- Наконец, установите в CardView в вашем макете android:layout_margin=»@dimen/xxx_card_margin»
Филе покрытия
До Android 5.0 CardView не обрезал элементы контента для соответствия закругленным углам, а вместо этого использовал альтернативные варианты заполнения, чтобы элементы контента не покрывали закругленные углы CardView. Свойство, которое управляет этим поведением, — cardPreventCornerOverlap, а значением по умолчанию является true. Настройка этого свойства не влияет на системы Android5.0 и более поздние версии, если только значение cardUseCompatPadding не равно true. На следующем рисунке показано сравнение влияния различных значений cardPreventCornerOverlap до версии Android5.0 (оставлено false, справа true):
Очевидно, что способ автоматического добавления отступов под значением по умолчанию нежелателен, поэтому необходимо установить для этого свойства значение false.
lift-on-touch
По данным официального сайтаMaterial motionЧасть руководства по спецификации интерактивных действий, карт, кнопок и других представлений должна иметь эффект взаимодействия с касанием, то есть ось Z в трехмерном пространстве смещается, что приводит к эффекту затемнения Используемый вместе с эффектом Ripple, официальный сайт дает хороший пример:
Достигнуть этого эффекта также очень просто: вы можете создать файл lift_on_touch.xml в каталоге res / drawable, который выглядит следующим образом:
Таким образом, значение translationZ динамически изменяется посредством анимации атрибута и изменяется от 0dp до 6dp вдоль оси Z. Затем назначьте его свойству android: stateListAnimator. Поскольку атрибут stateListAnimator применим только к Lollipop и выше, чтобы скрыть предупреждение о версии в xml, вы можете указать tools: targetApi = «lollipop».
Об этой функции нужно добавить точку. Файл lift_on_touch.xml здесь, строго говоря, принадлежит ресурсам anim, а также применим к API 21 и выше, поэтому его следует поместить в каталог res / anim-v21 логически, а затем присвоить @ anim / lift_on_touch Свойство stateListAnimator, а не метод @ drawable / lift_on_touch в этом примере. Но если поместить его в каталог res / anim-v21, появится сообщение об ошибке:
XML file should be in either “animator” or “drawable”,not “anim”
Хотя эта «ошибка» не влияет на компиляцию и работу, она все еще является проблемой для программистов, стремящихся к совершенству, поэтому в этом примере я решил поместить ее в каталог res / drawable, вы можете использовать ее по своему усмотрению.
Сводка CardView
CardView также имеет некоторые другие свойства для использования, такие как cardElevation для установки размера тени, contentPadding вместо обычного свойства android: padding и т. Д. Основы не представлены в этой статье. Об этом можно узнать на официальном сайте. Из вышеприведенного введения видно, что при использовании CardView в основном используются некоторые стандартные атрибуты конфигурации. Мы можем использовать атрибут style, чтобы инкапсулировать его в файл styles.xml для унифицированного управления, например:
Пожаловаться, компоновка этого CSDN действительно безмолвна, так же, как и после хорошего релиза, беспомощный
Источник