I can't work out why my CardView doesn't get the background color set by my style. According to this answer on another StackOverflow question here using the old AndroidSupport-library you should just be able to set it by adding this to the default AppTheme:
<item name="cardBackgroundColor">#ff00ab</item>
However, this doesn't change the color in any way for me. Normally setting the color through app:cardBackgroundColor="..."
works fine, but for my application I need it to work through the styles.
I also tested it using a new project and just adding the minimal steps to make it work, but it still doesn't have the card color set by the style...
Here is my activity_main.xml
:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/activity_main"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<androidx.cardview.widget.CardView
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="testing string"/>
</androidx.cardview.widget.CardView>
</RelativeLayout>
In my styles.xml
I've added the simple line above to the default Base application theme.
Thanks for any help solving my problem!
EDIT: The AppTheme is just the default AppTheme with the line added above. It finally looks like this:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
<item name="cardBackgroundColor">#ff00ab</item>
</style>
For me, what you've posted works on API 19 and 22, but does not work on API 28. The following works for me on all API levels:
Rather than defining cardBackgroundColor
in your app's theme, instead define cardViewStyle
. This is a "default" style that is applied to all CardViews (unless explicitly overridden by a style
attribute in the layout file).
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
...
<item name="cardViewStyle">@style/MyCardViewStyle</item>
</style>
<style name="MyCardViewStyle">
<item name="cardBackgroundColor">#ff00ab</item>
</style>
You can determine whether a widget supports a default style attribute by checking its source code. There will be a constructor that looks like this:
public CardView(@NonNull Context context, @Nullable AttributeSet attrs) {
this(context, attrs, R.attr.cardViewStyle);
}
Here, the third param is R.attr.cardViewStyle
, so we know that that's what our theme should define. For components that do not support default styles, this third parameter will be 0
instead.