15
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.
4

5 回答 5

23

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

chip.chipBackgroundColor = getColorStateList(/*your preferred color*/)
于 2018-11-20T13:12:29.870 回答
23

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

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

对于 Java:

chip.setChipBackgroundColor(ColorStateList.valueOf(ContextCompat.getColor(context, R.color.yourColor)));
于 2019-03-10T00:27:52.273 回答
6

使用方法setChipBackgroundColorResource

chip.setChipBackgroundColorResource(R.color.chip_selector_color);

否则使用方法setChipBackgroundColor

chip.setChipBackgroundColor(AppCompatResources.getColorStateList(context, R.color.chip_selector_color));
于 2019-10-05T10:01:11.127 回答
5
  • 尝试这个:
chip.setChipBackgroundColor(getResources().getColorStateList(R.color.Green));
于 2018-11-21T04:38:20.313 回答
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" />
于 2022-01-31T05:26:22.860 回答