CardView通过xml设置背景无效

使用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中设置背景无效,在代码中设置背景可行

完!

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容