美文网首页Android代码踩坑池
CardView通过xml设置背景无效

CardView通过xml设置背景无效

作者: 祥龙翔天 | 来源:发表于2020-03-27 13:21 被阅读0次

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

完!

相关文章

  • CardView通过xml设置背景无效

    使用CardView嵌套Layout时 显示的时候,背后会有一层黑乎乎的东西,运行后,显示出来的效果 查看源码发现...

  • CardView一些必要属性

    CardView_cardBackgroundColor:设置背景色 CardView_cardCornerRad...

  • CardView显示无效果

    昨晚用CardView实现布局的时遇到一个玄学,阴影显示,给他设置背景或者其他属性的时候,全部无效。但是As也没有...

  • Android UI 设置背景

    设置背景的途径 在代码中设置 在 xml 里设置 设置背景的颜色效果 通过 Android 原生颜色设置 通过 A...

  • Android MaterialDesign

    一、CardView 误区:设置背景颜色,没有圆角 解决:设置控件背景 二、FloatingActionButto...

  • CardView

    参考 CardView 源码解析 常用属性 CardView 的阴影的实现方式是通过为 CardView 设置 b...

  • Android Button设置Background无效问题

    在xml中给button设置背景色为白色,但是运行无效。依旧为紫色。 查询资料发现Android Material...

  • Meterial Design常见控件的使用(八):CardVi

    目录: CardView简介 CardView基本属性(xml文件中) 某些属性使用效果 CardView使用方法...

  • CardView margin

    CardView中设置margin属性无效果,后来查了一下,发现解析的时候要使用: 原来使用的:

  • iOS UITableViewHeaderFooterView无

    UITableViewHeaderFooterView直接设置背景色无效,需要设置contentView的背景色

网友评论

    本文标题:CardView通过xml设置背景无效

    本文链接:https://www.haomeiwen.com/subject/srtluhtx.html