Search code examples
androidxmlandroid-cardviewandroid-stylescardview

CardView custom style attributes


I read many other question about this stuff like this or this or this but no one work for me.

I need to create a custom style form CardView. This is my code:

style.xml

<resources >    
 ...
    <style name="CardViewStyle" parent="CardView">
        <item name="app:cardBackgroundColor">#d9edf7</item>
    </style>    
</resources>

my_card.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/CardViewStyle">

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:orientation="vertical">

        <TextView
            android:id="@+id/txvId"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

        <TextView
            android:id="@+id/txvDatetime"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />

    </LinearLayout>
</android.support.v7.widget.CardView>

In my app gradle file

compileSdkVersion 26
minSdkVersion 19
targetSdkVersion 26
implementation 'com.android.support:appcompat-v7:26.1.0'
compile 'com.android.support:recyclerview-v7:26.1.0'
compile 'com.android.support:cardview-v7:26.1.0'

Unlikely this do not work for me. Nothing happens, but I do not find the problem. If I do not use the custom style and do directly :

my_card.xml

    <?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    app:cardBackgroundColor="#d9edf7" >

        <LinearLayout
            android:layout_width="wrap_content"
            android:layout_height="match_parent"
            android:orientation="vertical">

            <TextView
                android:id="@+id/txvId"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <TextView
                android:id="@+id/txvDatetime"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

        </LinearLayout>
    </android.support.v7.widget.CardView>

It works fine. But I need to use a custom style.


Solution

  • don't set theme in cardview instead of style

    change this

    android:theme="@style/CardViewStyle"
    

    To

    style="@style/CardViewStyle"
    

    and it's work.