2

在棒棒糖之前的设备中,当在卡片视图上按下时,它会显示一个难看的灰色矩形,那么如何只为没有卡片阴影的卡片内容设置颜色?

这是我的 cardView XML

<android.support.v7.widget.CardView
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:id="@+id/card"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_margin="10dp"
    card_view:contentPadding="50dp"
    card_view:cardElevation="5dp"
    android:clickable="true"
    android:foreground="?android:attr/selectableItemBackground">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />
</android.support.v7.widget.CardView>

谢谢!

4

1 回答 1

0

我找到了解决我的问题的方法。

首先,创建一个名为CustomCardViewextends的自定义类CardView

然后重写该方法,在卡片按下状态发生变化时drawableStateChanged()调用该方法改变卡片背景颜色。setCardBackgroundColor()

最后,在你的布局文件中用这个 CustomCardView 替换 CardView。

此方案唯一的一个缺点是 CardView 在 Android 5.0 及更高版本上无法显示波纹按压效果。

希望这可以帮到你 :)

这是我的代码:

public class CustomCardView extends CardView {

public CustomCardView(Context context) {
    super(context);
    // TODO Auto-generated constructor stub
}

public CustomCardView(Context context, AttributeSet attrs) {
    super(context, attrs);
    // TODO Auto-generated constructor stub
}

public CustomCardView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    // TODO Auto-generated constructor stub
}

@Override
protected void drawableStateChanged() {
    if (isPressed()) {
        this.setCardBackgroundColor(getContext().getResources().getColor(R.color.card_view_pressed));
    } else {
        this.setCardBackgroundColor(getContext().getResources().getColor(R.color.card_view_normal));
    }
}
}
于 2015-06-10T13:08:08.850 回答