【问题标题】:Set background color of the material chip programmatically以编程方式设置材料芯片的背景颜色
【发布时间】:2019-04-22 21:38:21
【问题描述】:
Chip chip = new Chip(context);
chip.setBackgroundcolor(getResources().getColor(R.color.blue));

上面一行给出了错误:

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

【问题讨论】:

    标签: android material-components-android android-chips


    【解决方案1】:
    • 试试这个:
    chip.setChipBackgroundColor(getResources().getColorStateList(R.color.Green));
    

    【讨论】:

    • 此方法已弃用,请改用chip.setChipBackgroundColor(ColorStateList.valueOf(ContextCompat.getColor(context, R.color.white)));
    【解决方案2】:

    使用方法setChipBackgroundColorResource

    chip.setChipBackgroundColorResource(R.color.chip_selector_color);
    

    否则使用setChipBackgroundColor的方法

    chip.setChipBackgroundColor(AppCompatResources.getColorStateList(context, R.color.chip_selector_color));
    

    【讨论】:

      【解决方案3】:

      对于 Kotlin,你应该使用这个:

      chip.chipBackgroundColor = ColorStateList.valueOf(ContextCompat.getColor(context, R.color.yourColor))
      

      对于 Java:

      chip.setChipBackgroundColor(ColorStateList.valueOf(ContextCompat.getColor(context, R.color.yourColor)));
      

      【讨论】:

        【解决方案4】:

        您可以通过以下行(Kotlin)设置材料芯片的背景颜色

        chip.chipBackgroundColor = getColorStateList(/*your preferred color*/)
        

        【讨论】:

        • 以下行对我有用 Chip.setChipBackgroundColorResource(R.color.colorBlue);
        猜你喜欢
        • 2023-02-23
        • 1970-01-01
        • 1970-01-01
        • 2021-10-18
        • 1970-01-01
        • 2014-06-24
        • 2016-12-02
        • 1970-01-01
        • 2023-03-26
        相关资源
        最近更新 更多