Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 294
Ritesh Adulkar Avatar asked Nov 29 '18 05:11

Ritesh Adulkar


People also ask

How do you change the color of a chip when selected?

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.

What is chip group in Android Studio?

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 .


2 Answers

if you want change background color, you can try:

ChipDrawable chipDrawable = (ChipDrawable)chip.getChipDrawable();
chipDrawable.setChipBackgroundColorResource(R.color.colorPrimary);
like image 57
kk320 Avatar answered Sep 19 '22 06:09

kk320


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

like image 33
Manthan Patel Avatar answered Sep 22 '22 06:09

Manthan Patel