【问题标题】:CardView press effect in pre-lollipop device棒棒糖前设备中的 CardView 按下效果
【发布时间】:2014-12-29 12:28:59
【问题描述】:

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

这是我的 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>

谢谢!

【问题讨论】:

    标签: android android-cardview


    【解决方案1】:

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

    首先,创建一个名为 CustomCardView 的自定义类,该类扩展 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));
        }
    }
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-02-23
      • 2016-02-11
      • 2018-09-01
      • 2016-08-14
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多