使用CardView嵌套Layout时
<android.support.v7.widget.CardView
android:id="@+id/id_item_layout"
android:layout_width="160dp"
android:layout_height="93.333333dp"
app:cardCornerRadius="10dp"
app:cardElevation="5dp">
<!--嵌套一个layout-->
</android.support.v7.widget.CardView>
显示的时候,背后会有一层黑乎乎的东西,运行后,显示出来的效果

查看源码发现CardView会默认设置一个背景色
// If the theme colorBackground is light, use our own light color, otherwise dark
final float[] hsv = new float[3];
Color.colorToHSV(themeColorBackground, hsv);
backgroundColor = ColorStateList.valueOf(hsv[2] > 0.5f
? getResources().getColor(R.color.cardview_light_background)
: getResources().getColor(R.color.cardview_dark_background));
于是想,手动设置一个透明色去替换,应该就会好了
<android.support.v7.widget.CardView
android:id="@+id/id_item_layout"
android:layout_width="160dp"
android:layout_height="93.333333dp"
app:cardBackgroundColor="@android:color/transparent"
app:cardCornerRadius="10dp"
app:cardElevation="5dp">
<!--嵌套一个layout-->
</android.support.v7.widget.CardView>
可是,但是,but,运行后,显示出来的效果

我靠,这样还不如之前呢,于是想,手动设置一个背景吧
<android.support.v7.widget.CardView
android:id="@+id/id_item_layout"
android:layout_width="160dp"
android:layout_height="93.333333dp"
android:background="@drawable/item_default_bg"
app:cardBackgroundColor="@android:color/transparent"
app:cardCornerRadius="10dp"
app:cardElevation="5dp">
<!--嵌套一个layout-->
</android.support.v7.widget.CardView>
运行后,显示出来的效果

还是一样!没有变化。事实上,在这里设置任何背景都无效,这还怎么玩?
别急,是时候靠感觉了
xml中设置不行,去Java代码里面设置一下试试呢?
findViewById(R.id.id_item_layout).setBackground(getResources().getDrawable(R.drawable.item_default_bg));
运行后,显示出来的效果

结论:CardView在xml中设置背景无效,在代码中设置背景可行
完!
网友评论