我正在尝试扩展卡片 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/