The style on this component requires your app theme to be Theme.AppCompat

文章讲述了在使用overlay切换多主题时遇到AppBarLayout组件因主题不兼容引发的InflateException。问题的关键在于组件需要AppCompat主题。尝试更换activity和application的主题未成功,通过分析源码发现异常源于colorPrimary属性检查。解决方案是在自定义主题中添加colorPrimary及其相关属性。
摘要由CSDN通过智能技术生成

通过overlay切换多主题遇到layout里这个组件inflate异常 <com.google.android.material.appbar.AppBarLayout
Caused by: java.lang.IllegalArgumentException: The style on this component requires your app theme to be Theme.AppCompat (or a descendant).
做了几次尝试:
1.将activity主题换为Theme.AppCompat // 失败

2.将application主题也换位Theme.AppCompat // 失败

3.将<com.google.android.material.appbar.AppBarLayout去掉 // OK,但功能需要不能去掉

4.研究源码,找到异常点
com.google.android.material.internal.ThemeEnforcement#checkAppCompatTheme

public static void checkAppCompatTheme(@NonNull Context context) {
  checkTheme(context, APPCOMPAT_CHECK_ATTRS, APPCOMPAT_THEME_NAME);
}

这个组件会检测主题,通过代码看到
 

private static final int[] APPCOMPAT_CHECK_ATTRS = {R.attr.colorPrimary};

也就是要检测主题colorPrimary属性

private static void checkTheme(
    @NonNull Context context, @NonNull int[] themeAttributes, String themeName) {
  if (!isTheme(context, themeAttributes)) {
    throw new IllegalArgumentException(
        "The style on this component requires your app theme to be "
            + themeName
            + " (or a descendant).");
  }
}

这里可以看到异常信息,关键点在于com.google.android.material.internal.ThemeEnforcement#isTheme
 

private static boolean isTheme(@NonNull Context context, @NonNull int[] themeAttributes) {
  TypedArray a = context.obtainStyledAttributes(themeAttributes);
  for (int i = 0; i < themeAttributes.length; i++) {
    if (!a.hasValue(i)) {
      a.recycle();
      return false;
    }
  }
  a.recycle();
  return true;
}

从方法名可以看出是判断是否主题,这里有点不是太明白为啥是这个名字,不过无关紧要,这个方法就是检测传进来的主题属性是否在当前主题里都存在,如果有一个不存在则认为不是主题,从上面可以看出其实就是检测R.attr.colorPrimary属性是否存在,不存在就让你异常,所以解决办法自然有了,那就是在主题里添加这个属性,不过一般加三个,单独加colorPrimary也可以解决问题

<item name="colorAccent">@color/color_cursor</item>
<item name="colorPrimaryDark">@color/primary_dark_material_dark</item>
<item name="colorPrimary">@color/primary_material_dark</item>
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值