I want to set custom drawable background to Chip, just like that chip.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.bg_cutom_drawable));
But it is not working.It gives an error
java.lang.UnsupportedOperationException: Do not set the background resource; Chip manages its own background drawable.
It required a chipDrawable. How to create chipDrawable for same. I tried but not able to find out solution. Please suggest me it would be appreciate.
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.
A ChipGroup is used to hold multiple Chip s. By default, the chips are reflowed across multiple lines. Set the app:singleLine attribute to constrain the chips to a single horizontal line. If you do so, you'll usually want to wrap this ChipGroup in a HorizontalScrollView .
if you want change background color, you can try:
ChipDrawable chipDrawable = (ChipDrawable)chip.getChipDrawable();
chipDrawable.setChipBackgroundColorResource(R.color.colorPrimary);
Using this code you can generate multicolor chip.
add this code in oncreate() or anywhere in function
// "i" is integer value and it will be unique for every chip. In my case I have put in chip in FOR loop that why "i" is there
Chip chip = (Chip) LayoutInflater.from(getActivity()).inflate(R.layout.item_content_lang_chip, null);
chip.setText(contentLangModels.get(i).getContentDisplay());
chip.setId(i);
chip.setChipBackgroundColor(buildColorStateList(getActivity(),"#1e61d5","#2e2e37"));
chipGrpContentType.addView(chip);
Add below function in your activity
public ColorStateList buildColorStateList(Context context, String pressedColorAttr, String defaultColorAttr){
int pressedColor = Color.parseColor(pressedColorAttr);
int defaultColor = Color.parseColor(defaultColorAttr);
return new ColorStateList(
new int[][]{
new int[]{android.R.attr.state_checked},
new int[]{} // this should be empty to make default color as we want
}, new int[]{
pressedColor,
defaultColor
}
);
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With