繁体   English   中英

更改 CardView 的 hover 的背景颜色

[英]Change background color on hover of a CardView

我想在 Android Studio 中将背景颜色更改为我的 CardView,我想使用选择器,但我不知道我在做什么

这在我的代码中:

<androidx.cardview.widget.CardView
                android:id="@+id/card_ordina"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:layout_margin="15dp"
                app:cardBackgroundColor="@color/orange"
                app:cardCornerRadius="20dp">

                <ImageView
                    android:layout_width="80dp"
                    android:layout_height="80dp"
                    android:layout_gravity="center_horizontal"
                    android:layout_marginLeft="30dp"
                    android:layout_marginTop="20dp"
                    android:layout_marginRight="30dp"
                    android:layout_marginBottom="40dp"
                    android:background="@drawable/options"
                    android:backgroundTint="#F44336"
                    android:padding="10dp"
                    android:src="@drawable/carrello"
                    android:tint="@color/background" />

                <TextView
                    android:layout_width="wrap_content"
                    android:layout_height="wrap_content"
                    android:layout_gravity="bottom|center"
                    android:layout_marginBottom="5dp"
                    android:fontFamily="@font/title"
                    android:text="ORDINA"
                    android:textColor="@color/background"
                    android:textSize="18sp" />

            </androidx.cardview.widget.CardView>

您需要制作一个选择器并将以下属性设置为您的 CardView。

android:foreground="@drawable/card_foreground"
android:clickable="true"
android:focusable="true"

这是 card_foreground.xml 的代码,将其添加到项目的可绘制文件夹中。

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape android:shape="rectangle">
            <solid android:color="#e0F5AD6E"/>
            <corners android:radius="2dp" />
        </shape>
    </item>
    <item android:state_focused="true" android:state_enabled="true">
        <shape android:shape="rectangle">
            <solid android:color="#0f000000"/>
            <corners android:radius="2dp" />
        </shape>
    </item>
</selector>

您可以根据需要更改 state colors 和半径。 现在,当您单击 CardView 时,颜色将发生变化。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM