以编程方式设置材料芯片的背景颜色

20
Chip chip = new Chip(context);
chip.setBackgroundcolor(getResources().getColor(R.color.blue));

上述行会报错:

java.lang.UnsupportedOperationException: Do not set the background resource; Chip manages its own background drawable.
6个回答

32

对于 Kotlin,您应该使用这个:

chip.chipBackgroundColor = ColorStateList.valueOf(ContextCompat.getColor(context, R.color.yourColor))

对于Java:

chip.setChipBackgroundColor(ColorStateList.valueOf(ContextCompat.getColor(context, R.color.yourColor)));

它的工作是chip.chipBackgroundColor = ColorStateList.valueOf(ContextCompat.getColor(context, R.color.yourColor)) 谢谢您 - undefined

28

您可以通过以下代码(Kotlin)设置材料芯片的背景颜色:

chip.chipBackgroundColor = getColorStateList(/*your preferred color*/)

7
以下代码对我很有用: Chip.setChipBackgroundColorResource(R.color.colorBlue); 它将设置芯片的背景颜色为蓝色。 - Ganesh Acharya

8
使用方法 setChipBackgroundColorResource
chip.setChipBackgroundColorResource(R.color.chip_selector_color);

否则,请使用方法 setChipBackgroundColor
chip.setChipBackgroundColor(AppCompatResources.getColorStateList(context, R.color.chip_selector_color));

6
  • 试试这个:
chip.setChipBackgroundColor(getResources().getColorStateList(R.color.Green));

1
该方法已被弃用,请使用 chip.setChipBackgroundColor(ColorStateList.valueOf(ContextCompat.getColor(context, R.color.white))); 替代。 - Amitoj

1

在xml中使用backgroundTint

            <com.google.android.material.chip.Chip
                android:id="@+id/timetext_id"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginHorizontal="40dp"
                android:layout_weight="1"
                android:backgroundTint="#39b8db"
                android:gravity="center"
                android:padding="5dp"
                android:text="Time"
                android:textAlignment="center"
                android:textColor="@color/white" />

0
在 Kotlin 中:
```chip.chipBackgroundColor = ContextCompat.getColorStateList(this.context, R.color.**yourcolorid**)```

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