Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set background color of the material chip programmatically

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.
like image 783
Ganesh Acharya Avatar asked Nov 20 '18 12:11

Ganesh Acharya


People also ask

How to set Chip background color programmatically?

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

How do I change the background color in programmatically?

xml which is under the values folder,then you should call the following: root. setBackgroundColor(getResources(). getColor(R.color.name));

How do I change the color of a selected chip?

So you can use the setChipBackgroundColor(ColorStateList cl) method to set the color of your chip and then you can add an setOnClickListener(new ...) to toggle with selection and non-selection like the following code: yourchip. setOnClickListener(new View.


4 Answers

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

chip.chipBackgroundColor = getColorStateList(/*your preferred color*/)
like image 116
Ravi Kumar Avatar answered Oct 13 '22 10:10

Ravi Kumar


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)));
like image 28
SobaDeveloper Avatar answered Oct 13 '22 10:10

SobaDeveloper


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));
like image 8
Gabriele Mariotti Avatar answered Oct 13 '22 11:10

Gabriele Mariotti


  • Try this:
chip.setChipBackgroundColor(getResources().getColorStateList(R.color.Green));
like image 5
Ritu Tandel Avatar answered Oct 13 '22 09:10

Ritu Tandel