NavigationView自定义主题中Toolbar引发崩溃问题求助
看起来你踩了一个自定义主题搭配Toolbar时很常见的坑,咱们一步步拆解问题并解决:
错误原因分析
先看核心报错信息:
java.lang.IllegalStateException: This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_SUPPORT_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead.
问题出在主题配置的冲突上:
你在AndroidManifest.xml里给MainActivity指定了@style/NoActionBar主题(这个主题确实禁用了系统默认ActionBar),但你在onCreate的第一行调用了setTheme(MyThemes(this).getMyThemeId()),这直接覆盖了Manifest的主题设置。而你定义的彩色主题(比如MyLightTheme.Red)是直接继承自MyLightTheme的——这个父主题本身是Theme.AppCompat.Light,默认自带ActionBar,没有禁用它的配置,所以系统还是会自动创建默认ActionBar,等到你调用setSupportActionBar(toolbar)时就会触发冲突崩溃。
修复方案
方案一:调整主题继承关系(推荐)
把你的彩色主题改成继承自NoActionBar,这样它们会自动继承禁用ActionBar的配置:
<style name="MyLightTheme" parent="Theme.AppCompat.Light"/> <style name="NoActionBar" parent="MyLightTheme"> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item> <item name="windowActionBarOverlay">true</item> </style> <!-- 修改彩色主题的parent为NoActionBar --> <style name="MyLightTheme.Red" parent="NoActionBar"> <item name="colorPrimary">@color/red_4_100</item> <item name="colorPrimaryDark">@color/red_6_100</item> <item name="colorAccent">@color/red_6_100</item> </style> <!-- 其他彩色主题也同理修改parent属性 -->
方案二:在基础主题中直接禁用ActionBar
如果你希望所有基于MyLightTheme的主题都默认不带ActionBar,可以直接在基础主题里添加禁用配置,省去修改每个彩色主题的麻烦:
<style name="MyLightTheme" parent="Theme.AppCompat.Light"> <item name="windowActionBar">false</item> <item name="windowNoTitle">true</item> </style> <!-- 此时NoActionBar主题可以保留或删除,基础主题已包含禁用配置 --> <style name="MyLightTheme.Red" parent="MyLightTheme"> <item name="colorPrimary">@color/red_4_100</item> <item name="colorPrimaryDark">@color/red_6_100</item> <item name="colorAccent">@color/red_6_100</item> </style>
额外检查点
- 确保你的
toolbar.xml布局没有多余的主题配置冲突,保持简洁即可:
<androidx.appcompat.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?attr/actionBarSize" android:background="?attr/colorPrimary" android:elevation="4dp" />
- 你已经正确把
setTheme的调用放在了super.onCreate(savedInstanceState)之前,这个操作没问题,继续保持即可。
完成上述修改后,启动应用就不会再出现崩溃,Toolbar也能正常和ActionBarDrawerToggle配合,实现NavigationView的正常显示与切换了。
内容的提问来源于stack exchange,提问作者Akshdeep Singh

