Chip:此组件上的样式要求您的应用程序主题为 Theme.MaterialComponents (或后代)

问题描述 投票:0回答:1

我想在我的项目中向 ChipGroup 添加一个 Chip 视图,但总是出现以下错误

我在 Activity 中的代码

 for (int i = 0; i < names.size(); i++) {
      Chip chip = new Chip(getApplicationContext());
      chip.setText(names.get(i));
      chip.setId(i);
      chipGroup.addView(chip);
    }

错误是

java.lang.IllegalArgumentException: The style on this component requires your app theme to be Theme.MaterialComponents (or a descendant).
        at com.google.android.material.internal.ThemeEnforcement.checkTheme(ThemeEnforcement.java:248)
        at com.google.android.material.internal.ThemeEnforcement.checkMaterialTheme(ThemeEnforcement.java:222)
        at com.google.android.material.internal.ThemeEnforcement.checkCompatibleTheme(ThemeEnforcement.java:150)
        at com.google.android.material.internal.ThemeEnforcement.obtainStyledAttributes(ThemeEnforcement.java:81)
        at com.google.android.material.chip.ChipDrawable.loadFromAttributes(ChipDrawable.java:334)
        at com.google.android.material.chip.ChipDrawable.createFromAttributes(ChipDrawable.java:276)
        at com.google.android.material.chip.Chip.<init>(Chip.java:193)
        at com.google.android.material.chip.Chip.<init>(Chip.java:186)
        at com.google.android.material.chip.Chip.<init>(Chip.java:182)
        

我的应用主题

 <style name="AppTheme" parent="Theme.MaterialComponents.Light.DarkActionBar">
    <!-- Customize your theme here. -->
    <item name="colorPrimary">@color/colorPrimary</item>
    <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
    <item name="colorAccent">@color/colorAccent</item>
   
  </style>

如上面的代码所示,我的主题是正确的!

android android-theme material-components-android android-chips
1个回答
0
投票

过了一会儿我发现需要将 Activity 传递给 Chip 而不是传递 context

代码就在下面。

 Chip chip = new Chip(this);
© www.soinside.com 2019 - 2024. All rights reserved.