Android Material Design 实现 Toolbar 替换 ActionBar 错误解决
Android Material Design 实现 Toolbar 替换 ActionBar 错误解决
报错信息:
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.
错误原因:
该错误是由于在主题中同时使用了ActionBar和Toolbar导致的冲突。
解决方法:
在主题中设置windowActionBar为false,以使用Toolbar替代ActionBar。
步骤:
- 修改styles.xml文件
<resources>
<string name='app_name'>MaterialTest</string>
<style name='AppTheme' parent='Theme.AppCompat.Light.NoActionBar'>
<!-- Customize your theme here. -->
<item name='colorPrimary'>@color/colorPrimary</item>
<item name='colorPrimaryDark'>@color/colorPrimaryDark</item>
<item name='colorAccent'>@color/colorAccent</item>
<item name='android:textColorPrimary'>@color/colorPrimary</item>
<item name='android:windowBackground'>@color/colorPrimaryDark</item>
<item name='android:navigationBarColor'>@color/colorPrimary</item>
</style>
<style name='AppTheme.DarkActionBar' parent='Theme.AppCompat.Light.DarkActionBar'>
<!-- Customize your theme here. -->
<item name='colorPrimary'>@color/colorPrimary</item>
<item name='colorPrimaryDark'>@color/colorPrimaryDark</item>
<item name='colorAccent'>@color/colorAccent</item>
<item name='android:textColorPrimary'>@color/colorPrimary</item>
<item name='android:windowBackground'>@color/colorPrimaryDark</item>
<item name='android:navigationBarColor'>@color/colorPrimary</item>
</style>
</resources>
- 修改MainActivity的onCreate方法
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
// 使用AppTheme主题
setTheme(R.style.AppTheme)
setContentView(binding.root)
setSupportActionBar(binding.toolbar)
}
通过以上修改,即可解决该问题。
原文地址: https://www.cveoy.top/t/topic/qwtk 著作权归作者所有。请勿转载和采集!