Ritesh Adulkar
Ritesh Adulkar

Reputation: 881

Set custom chipDrawable background to Chip

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.

Upvotes: 13

Views: 8510

Answers (4)

Manthan Patel
Manthan Patel

Reputation: 1852

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
        }
        );
    }

enter image description here

Upvotes: 2

Shubhendra Singh
Shubhendra Singh

Reputation: 456

If someone is using a material chip inside a dialog and getting a crash with same above error then you need to remove background attribute for your dialog set from styles.

Upvotes: 0

kk320
kk320

Reputation: 96

if you want change background color, you can try:

ChipDrawable chipDrawable = (ChipDrawable)chip.getChipDrawable();
chipDrawable.setChipBackgroundColorResource(R.color.colorPrimary);

Upvotes: 8

Amir Mohsenian
Amir Mohsenian

Reputation: 94

Do not use the android:background attribute. It will be ignored because Chip manages its own background Drawable chip document

Upvotes: 0

Related Questions