10

我想将自定义可绘制背景设置为 Chip,就像那个 chip.setBackgroundDrawable(context.getResources().getDrawable(R.drawable.bg_cutom_drawable));

但它不起作用。它给出了一个错误

java.lang.UnsupportedOperationException: Do not set the background resource; Chip manages its own background drawable.

它需要一个chipDrawable。如何为其创建chipDrawable。我试过但无法找到解决方案。请建议我,这将不胜感激。

4

4 回答 4

8

如果要更改背景颜色,可以尝试:

ChipDrawable chipDrawable = (ChipDrawable)chip.getChipDrawable();
chipDrawable.setChipBackgroundColorResource(R.color.colorPrimary);
于 2019-11-21T05:44:15.237 回答
1

使用此代码,您可以生成多色芯片。


将此代码添加到 oncreate() 或函数中的任何位置

// "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);

在您的活动中添加以下功能

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

在此处输入图像描述

于 2020-10-21T13:24:08.880 回答
0

不要使用该android:background属性。它将被忽略,因为 Chip 管理自己的后台 Drawable 芯片文档

于 2018-12-01T07:09:14.250 回答
0

如果有人在对话框中使用材料芯片并出现与上述相同错误的崩溃,那么您需要从样式中删除对话框集的背景属性。

于 2020-10-02T11:09:21.710 回答