2

专业开发者。我将尝试以编程方式更改卡片视图背景和笔触颜色,但始终card.setCardBackgroundColor()覆盖笔触颜色。静态地在 XML 中,它运行良好。但是以编程方式它会产生这样的效果。

val colorWithAlpha = ColorUtils.setAlphaComponent(tagColor, 128)
tagView.card.setStrokeColor(ColorStateList.valueOf(colorWithAlpha))
tagView.card.setCardBackgroundColor(ColorStateList.valueOf(tagColor))

同样适用于:card.backgroundTintList = ColorStateList.valueOf(tagColor)

XML:

<?xml version="1.0" encoding="utf-8"?>
<com.google.android.material.card.MaterialCardView xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/card"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    app:cardBackgroundColor="#DB8A61"
    app:cardCornerRadius="8dp"
    app:cardElevation="0dp"
    app:cardUseCompatPadding="true"
    app:cardPreventCornerOverlap="true"
    app:strokeColor="#EBD3C7"
    app:strokeWidth="4dp">

    <com.google.android.material.textview.MaterialTextView
        android:id="@+id/tag_text"
        style="@style/SmallLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:lines="1"
        android:paddingStart="8dp"
        android:paddingTop="4dp"
        android:paddingEnd="8dp"
        android:paddingBottom="4dp"
        android:textColor="@color/white"
        app:autoSizeMaxTextSize="100sp"
        app:autoSizeMinTextSize="5sp"
        app:autoSizeStepGranularity="1sp"
        app:autoSizeTextType="uniform"
        tools:text="Some Text" />

</com.google.android.material.card.MaterialCardView>

外观:XML:在此处输入图像描述

在代码中这样做:

private fun createAddTagView(tagName: String, tagColor: Int, container: ViewGroup) {
        val tagView = LayoutTagBinding.inflate(inflater, container, true)
        tagView.tagText.text = tagName
        val colorWithAlpha = ColorUtils.setAlphaComponent(tagColor, 128)
        tagView.card.setStrokeColor(ColorStateList.valueOf(colorWithAlpha))
        tagView.card.setCardBackgroundColor(ColorStateList.valueOf(tagColor))
    }

在此处输入图像描述

拆除时:tagView.card.setCardBackgroundColor(ColorStateList.valueOf(tagColor))

在此处输入图像描述

当没有程序化更改(由 设置的颜色XML)看起来像预期的那样:

在此处输入图像描述

如何让它像在XML节目中一样?

4

1 回答 1

0

我认为问题不在于MaterialCardView背景/笔画方法;但是布局中使用的颜色阴影与以编程方式使用的颜色不同。

布局中使用的颜色:

app:cardBackgroundColor="#DB8A61"
app:strokeColor="#EBD3C7"

但是以编程方式,您使用tagColoralpha 通道并向其添加colorWithAlpha; 你没有提供tagColor; 但是添加 128 alpha 分量不会有太大变化;这与完全没有 alpha 分量的布局颜色完全不同。

因此,要以编程方式使用相同的颜色,只需重用相同的布局颜色而不使用 alpha 组件:

tagView.card.setCardBackgroundColor(ColorStateList.valueOf(Color.parseColor("#DB8A61")))
tagView.card.setStrokeColor(ColorStateList.valueOf(Color.parseColor("#EBD3C7")))
于 2021-11-17T19:19:50.010 回答