- Cardview with Recyclerview Android Example [beginners]
- Cardview XML attribute
- Cardview android example with Recyclerview
- Step 1 — Adding dependencies
- Android CardView Using Images as Background in CardView (Pre-Lollipop device issues)
- Example
- Изменение цвета фона CardView программно
- РЕШЕНИЕ
- [MaterialCardView] Background color can’t be set to white #1402
- Comments
- risalfajar commented Jun 12, 2020
- risalfajar commented Jun 12, 2020 •
- ardhikarafi commented Jun 16, 2020
- consp1racy commented Jun 17, 2020
- henningBunk commented Aug 21, 2020
- LoicJ commented Aug 25, 2020
- gabrielemariotti commented Aug 25, 2020 •
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.
Источник
Android CardView Using Images as Background in CardView (Pre-Lollipop device issues)
Example
While using Image/Colour as an background in a CardView, You might end up with slight white paddings (If default Card colour is white) on the edges. This occurs due to the default rounded corners in the Card View. Here is how to avoid those margins in Pre-lollipop devices.
We need to use an attribute card_view:cardPreventCornerOverlap=»false» in the CardView. 1). In XML use the following snippet.
- In Java like this cardView.setPreventCornerOverlap(false) .
Doing so removes an unwanted padding on the Card’s edges. Here are some visual examples related to this implementation.
1 Card with image background in API 21 (perfectly fine)
2 Card with image background in API 19 without attribute (notice the paddings around image)
3 FIXED Card with image background in API 19 with attribute cardView.setPreventCornerOverlap(false) (Issue now fixed)
Also read about this on Documentation here
Original SOF post here
Источник
Изменение цвета фона CardView программно
CardView имеет атрибут card_view:cardBackgroundColor для определения цвета фона. Этот атрибут работает нормально.
В то же время не существует способа динамического изменения цвета.
Я просто пробовал такие решения, как:
Или используя макет внутри cardView
Эти решения не работают, потому что у карты есть cardCornerRadius.
Используйте свойство card_view: cardBackgroundColor:
Вы можете использовать это в XML
Я использовал этот код для программного программирования:
Или в XML вы можете использовать этот код:
Способ, который он задает в методе initialize использует защищенный класс RoundRectDrawable , например:
Это некрасиво, но вы можете расширить этот класс. Что-то вроде:
РЕДАКТИРОВАТЬ
Кажется, что нет лучшего способа сделать это.
Немного поздно здесь и отчасти от темы, поскольку это не программно, но я считаю, что лучше всего устанавливать стили для виджетов, и вы можете сделать это, чтобы CardView просто создал стиль, который сохранит ваш xml-фильтр …
Это используется android.support.v7.widget.CardView
А затем задание стиля в файле макета:
Вам нужно импортировать библиотеку appcompat-v7 с помощью студии Android через gradle:
надеюсь это поможет. Счастливое кодирование
Я столкнулся с той же проблемой при попытке создать картотеку программно, что странно, так это то, что глядя на документ https://developer.android.com/reference/android/support/v7/widget/CardView.html#setCardBackgroundColor%28int % 29 , ребята Google обнародовали api, чтобы изменить цвет фона в виде карты, но странно, что мне не удалось получить доступ к нему в библиотеке поддержки, поэтому вот что сработало для меня:
Делая это, мне удается сохранить тень карты и закругленные углы.
В JAVA
Андроид использует цвета ARGB. Вы можете использовать это (0xFF + RGB COLOR) – Жестко-кодированный цвет.
Для тех, кто задается вопросом, откуда появилось это имя «card_view». Это фактически пространство имен, и таким образом вы можете его создать …
Здесь вторая строка (начиная с начала) создает пространство имен .. и последняя строка из последней – это xml-версия ответа этой java-версии вопроса. Haha Cheers!
У меня такая же проблема на Xamarin.Android – VS (2017)
Решение, которое сработало для меня:
РЕШЕНИЕ
В файле XML добавьте:
И в элементе android.support.v7.widget.CardView добавьте это свойство:
Вы также можете добавить cardElevation и cardElevation .
Если вы хотите отредактировать cardview программно, вам просто нужно использовать этот код: Для (C #)
И теперь вы можете менять цвет фона программно, не теряя границы, угловой радиус и высоту.
Источник
[MaterialCardView] Background color can’t be set to white #1402
Comments
risalfajar commented Jun 12, 2020
Description:
I’m trying to set the cardBackgroundColor to #FFF, but it turns to grey. It can’t be set to white unless I added foregroundTint with #FFF too.
It works normally with colors other than white.
You can view the screenshot here
Expected behavior:
It should be pure white #FFF
Source code:
Android API version:
API version for Preview: 29
Material Library version:
1.1.0
Device:
Android Studio 4.0
Note:
Changing the app theme to other than Theme.MaterialComponents.Light seems to fix the issue, but I don’t want to change the app theme.
The text was updated successfully, but these errors were encountered:
risalfajar commented Jun 12, 2020 •
UPDATE
I looked into material-1.1.0 library values.xml and found out that they set this:
@color/mtrl_card_view_foreground «
I don’t know why in Preview the cardForegroundColor doesn’t show as @android:color/transparent knowing that it is neither checked nor dragged.
My temporary workaround is adding app:cardForegroundColor=»@android:color/transparent» to CardView in my layout.
ardhikarafi commented Jun 16, 2020
consp1racy commented Jun 17, 2020
Probably another case of using -1 (which in fact is 0xffffffff aka white) as a default color marker, the code is littered with this nonsense.
henningBunk commented Aug 21, 2020
I got the same problem but the workaround setting the foreground color to transparent does not work for me. What does work for me is setting the cardElevation to 0dp. Only than I get a white background. Problem is I am losing the shadow of the card and therefore the card isn’t recognizable anymore.
Any solution not get darker colors with increasing elevation?
LoicJ commented Aug 25, 2020
I had the same issue and I noticed by having a look to the source code that an overlay was drawn on the card background when it has some elevation defined.
Try adding false to your theme or try defining a ThemeOverlay overriding this value and apply it to your CardView. It should solve your problem.
gabrielemariotti commented Aug 25, 2020 •
It is not a bug, it is related to the Elevation Overlays.
Shadows are less effective in an app using a dark theme, because they will have less contrast with the dark background colors and will appear to be less visible. In order to compensate for this, Material surfaces in a dark theme become lighter at higher elevations, when they are closer to the implied light source.
This is accomplished via elevation overlays, which are semi-transparent white ( colorOnSurface ) overlays that are conceptually placed on top of the surface color. The semi-transparent alpha percentage is calculated using an equation based on elevation, which results in higher alpha percentages at higher elevations, and therefore lighter surfaces.
By default the elevationOverlayEnabled (whether the elevation overlay functionality is enabled) is false in Light themes, true in Dark themes.
Just an example with a MaterialCardView with app:cardElevation=»4dp» and app:cardElevation=»8dp» .
Light mode:
If you want to disable it in a dark theme just add in your app theme:
false
Источник