Set background color of the material chip programmatically
Asked Answered
M

6

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

The above line gives the error:

java.lang.UnsupportedOperationException: Do not set the background resource; Chip manages its own background drawable.
Modulate answered 20/11, 2018 at 12:32 Comment(0)
C
28

You can set background color of material chip by following line (Kotlin)

chip.chipBackgroundColor = getColorStateList(/*your preferred color*/)
Cumulous answered 20/11, 2018 at 13:12 Comment(1)
the following line worked for me Chip.setChipBackgroundColorResource(R.color.colorBlue);Modulate
W
32

For Kotlin, you should use this:

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

For Java:

chip.setChipBackgroundColor(ColorStateList.valueOf(ContextCompat.getColor(context, R.color.yourColor)));
Waft answered 10/3, 2019 at 0:27 Comment(1)
its works chip.chipBackgroundColor = ColorStateList.valueOf(ContextCompat.getColor(context, R.color.yourColor)) thank uBiestings
C
28

You can set background color of material chip by following line (Kotlin)

chip.chipBackgroundColor = getColorStateList(/*your preferred color*/)
Cumulous answered 20/11, 2018 at 13:12 Comment(1)
the following line worked for me Chip.setChipBackgroundColorResource(R.color.colorBlue);Modulate
C
8

Use the method setChipBackgroundColorResource:

chip.setChipBackgroundColorResource(R.color.chip_selector_color);

Otherwise use the method setChipBackgroundColor

chip.setChipBackgroundColor(AppCompatResources.getColorStateList(context, R.color.chip_selector_color));
Cappello answered 5/10, 2019 at 10:1 Comment(0)
N
6
  • Try this:
chip.setChipBackgroundColor(getResources().getColorStateList(R.color.Green));
Nuli answered 21/11, 2018 at 4:38 Comment(1)
This method is deprecated, please use chip.setChipBackgroundColor(ColorStateList.valueOf(ContextCompat.getColor(context, R.color.white))); insteadFabian
B
1

use backgroundTint in xml

            <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" />
Bibliomania answered 31/1, 2022 at 5:26 Comment(0)
A
0

In Kotlin

chip.chipBackgroundColor = ContextCompat.getColorStateList(this.context,R.color.**yourcolorid**)

Amil answered 29/12, 2022 at 8:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.