android - BitmapDrawable 无法转换为 RoundRectDrawableWithShadow

标签 android android-widget android-cardview

我正在尝试扩展卡片 View 来设置背景图像。我知道普通的卡片 View 无法做到这一点。我在网上搜索并找到了很多为卡片 View 设置背景颜色的解决方案,但没有为图像设置背景颜色的解决方案。

我的代码这样做:

public class CCView extends CardView {

    public  CCView (Context context) {
        super(context);
        init();
    }

    public CCView (Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public CCView (Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }


    private void init() {

       setBackground(getResources().getDrawable(R.drawable.cc_background));

    }
}

当我从 XML 填充代码时出现此异常

android.graphics.drawable.BitmapDrawable cannot be cast to android.support.v7.widget.RoundRectDrawableWithShadow

有什么解决办法吗?

最佳答案

当 CardView 扩展 FrameLayout 时,您可以在其之上分层布局。为了解决您遇到的问题,我尝试在 View 中的所有其他元素“下方”添加一个空白 View ,然后将该 View 设置为继承其父级的状态。像这样的事情:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:card_view="http://schemas.android.com/apk/res-auto"
android:layout_height="match_parent"
android:layout_width="match_parent"
card_view:cardBackgroundColor="#DDFFFFFF"
card_view:cardElevation="@dimen/card_elevation">

    <View
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:duplicateParentState="true"
        android:background="@drawable/card_background"/>

    <LinearLayout
    ....
    ....
    ....
    /LinearLayout>

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

关于android - BitmapDrawable 无法转换为 RoundRectDrawableWithShadow,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29148641/

相关文章:

java - 自定义 setDropDownViewResource 微调项的示例

java - 配置更改后小部件不刷新

android - 如何将主要 Activity 和日期选择器分离到自己的类(class)

Android Material 默认颜色

android - 获取 Cardview 背景色

java - Android SQLite 查询顺序问题

android - Android 5.0 (Lollipop) 上的海拔无法正常工作

android - 'package :flutter/src/widgets/will_pop_scope. dart':断言失败:第 135 行 pos 12: '_route == ModalRoute.of(context)':不正确

java - Android奇怪的ComponentInfo NullPointerException

android - CardView 中的 ImageView 在 Android 4.3 上不显示半径