如何创建具有半透明背景颜色和圆角的CardView?

3
我正在尝试使用背景色#88FFFFFF和圆角制作CardView。但是在Android Studio中,圆角会变得不透明,并且在我的设备上整个边框也会变得不透明。以下是代码:
<android.support.v7.widget.CardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="100dp"
    android:layout_height="100dp"
    app:cardBackgroundColor="#88FFFFFF"
    app:cardElevation="2dp"
    app:cardCornerRadius="12dp">

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

这里是结果:

sad

有没有一种方法可以在不创建背景drawable的情况下解决这个问题?

28.0.0,同时我正在使用深色应用主题(Theme.AppCompat.NoActionBar)。 - Aayush Tyagi
4个回答

0
我在Xamarin.Android中遇到了CardView的问题,并找到了以下解决方案:
这是C#/Xamarin代码,但Java/Kotlin代码应该很相似。
      // There is a bug with CardView
      // Where setting a semi-transparent colour + corner radius + elevation will display a border with the opaque (a=255) colour.
      // To resolve this I'm manually calculating the desired colour (with a=255/2) and using an 
      // Android.Graphics.Color without using the alpha channel
 
      float opacity = 0.5f;
      var color = GetDesiredColorOpaque();
      var viewBgColor = GetViewBgColor(); 
      var desiredColor = new Color(color.R, color.G, color.B, color.A / 2); // not used - but resulting flattenedCardColor will look equivalent without transparency
 
      // Formula based on https://filosophy.org/code/online-tool-to-lighten-color-without-alpha-channel/
      // NB this only works because we're not really needing transparency i.e. the resulting card is not transparent, it is just colored as if it was transparent and behind it was just empty viewBgColor 
      var flattenedCardColor = new Color(
        r: (byte) (opacity * color.R + (1 - opacity) * viewBgColor.R),
        g: (byte) (opacity * color.G + (1 - opacity) * viewBgColor.G),
        b: (byte) (opacity * color.B + (1 - opacity) * viewBgColor.B),
        a: (byte) 255);
      
      cardView.CardBackgroundColor = Android.Content.Res.ColorStateList.ValueOf(flattenedCardColor);

请注意,此解决方案通过使用不透明度方程计算所需的CardView背景颜色来工作,因此它实际上不会使CardView透明。我这样做是因为我假设这个问题是由于CardView和半透明颜色存在一些错误引起的,因为没有任何提议的解决方案适用于我的用例(需要以编程方式设置CardView颜色)。
您得到的结果是正确着色的CardView背景,就好像透明度正在alpha通道中设置一样,并且在使用cardElevation和/或cardCornerRadius时没有视觉错误。
感谢https://filosophy.org/code/online-tool-to-lighten-color-without-alpha-channel/提供的方程式。

0

在CardView内部使用线性布局,将线性布局的背景设置为"#88FFFFFF"。

<CardView>
    <LinearLayout background=""></LinearLayout>
</CardView>

0

试试这个

<android.support.v7.widget.CardView
        android:layout_width="100dp"
        android:layout_height="100dp"
        app:cardBackgroundColor="#88FFFFFF"
        app:cardCornerRadius="6dp"
        app:cardUseCompatPadding="true"
        app:cardElevation="5dp">

0
尝试删除高程(elevation),它在新的MaterialCardView组件中可用。
app:cardElevation="0dp"
app:cardMaxElevation="0dp"

您还可以添加笔画,例如:

app:strokeColor="#f9d5e9"
app:strokeWidth="1.5dp"

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接