【问题标题】:Set custom chipDrawable background to Chip将自定义chipDrawable背景设置为Chip
【发布时间】:2018-11-29 05:49:38
【问题描述】:

我想为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。我试过但无法找到解决方案。 请建议我,不胜感激。

【问题讨论】:

  • 不确定是不是你的情况,但是有chipStrokeColorchipStrokeWidth属性来设置笔触,那么你可以使用颜色资源而不是drawable。

标签: android-chips


【解决方案1】:

如果你想改变背景颜色,你可以试试:

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

【讨论】:

    【解决方案2】:

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


    将此代码添加到 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
            }
            );
        }
    

    【讨论】:

    • 谢谢你,不管出于什么原因Chip.setBackgroundColor() 没用。
    【解决方案3】:

    不要使用android:background 属性。它将被忽略,因为 Chip 管理自己的背景 Drawable chip document

    【讨论】:

    • 嘿,我知道,它管理自己的可绘制对象。我想知道我将如何创建 chipDrawable
    【解决方案4】:

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

    【讨论】:

      猜你喜欢
      • 2020-01-06
      • 1970-01-01
      • 2011-12-27
      • 1970-01-01
      • 2011-08-22
      • 1970-01-01
      • 2018-06-29
      • 2021-05-30
      • 1970-01-01
      相关资源
      最近更新 更多