How to Change CardView background color from a theme

泄露秘密 提交于 2021-02-10 20:27:06

问题


In an app that has multiple themes, how would you change the background color of the CardView from the styles file?

styles.xml

<style name="AppTheme1" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorPrimary">@color/colorPrimaryTheme1</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDarkTheme1</item>
        <item name="colorAccent">@color/colorAccentTheme1</item>
</style>

<style name="AppTheme2" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorPrimary">@color/colorPrimaryTheme2</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDarkTheme2</item>
        <item name="colorAccent">@color/colorAccentTheme2</item>
</style>

<style name="AppTheme3" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorPrimary">@color/colorPrimaryTheme3</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDarkTheme3</item>
        <item name="colorAccent">@color/colorAccentTheme3</item>
</style>

CardView

<androidx.cardview.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/cardView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginStart="16dp"
    android:layout_marginTop="16dp"
    android:layout_marginEnd="16dp"
    android:elevation="4dp"
    app:cardCornerRadius="15dp">

I want to change the background color for each theme and I'm hoping to accomplish this in the styles.xml file.


回答1:


Try the below line of code

Write the below line of code in style.xml

    <style name="CustomCardview1" parent="CardView">
          <item name="cardBackgroundColor">#F3921F</item>
          <item name="android:layout_width">match_parent</item>
          <item name="android:layout_height">wrap_content</item>
         <item name="android:layout_margin">10dp</item>
     </style>

    <style name="CustomCardview2" parent="CardView">
          <item name="cardBackgroundColor">#F3931F</item>
          <item name="android:layout_width">match_parent</item>
          <item name="android:layout_height">wrap_content</item>
         <item name="android:layout_margin">10dp</item>
     </style>

Write the below line of code in layout where you need the cardview

 <android.support.v7.widget.CardView
      style="@style/CustomCardview">      

hope it will help for you



来源:https://stackoverflow.com/questions/58260102/how-to-change-cardview-background-color-from-a-theme

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!