Chip组件报错:要求应用主题为Theme.MaterialComponents或其子类
问题:动态添加Chip到ChipGroup时触发主题兼容错误
问题场景
项目中尝试向ChipGroup动态添加Chip视图时,持续出现主题兼容错误,但应用主题已配置为MaterialComponents系列。
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>
解决方案
错误根源是创建Chip时使用了getApplicationContext()——全局Application的主题并未继承MaterialComponents主题(即便Activity主题是)。只需替换为当前Activity的上下文即可修复:
for (int i = 0; i < names.size(); i++) { // 使用当前Activity上下文替代Application上下文 Chip chip = new Chip(YourActivityName.this); chip.setText(names.get(i)); chip.setId(i); chipGroup.addView(chip); }
也可以通过显式指定Chip的Material风格来解决:
Chip chip = new Chip(getApplicationContext(), null, R.style.Widget_MaterialComponents_Chip_Entry);
内容的提问来源于stack exchange,提问作者abolfazl bazghandi
相关产品推荐
相关产品推荐

