Android Toolbar 使用教程:解决'This Activity already has an action bar supplied by the window decor' 错误
Android Toolbar 使用教程:解决'This Activity already has an action bar supplied by the window decor' 错误
本文将介绍在 Android 应用中使用 Toolbar 控件时的常见错误 'This Activity already has an action bar supplied by the window decor' 的解决方法,并提供代码示例和详细步骤。
错误原因
该错误通常是由于在主题中同时设置了 windowActionBar 和 windowNoTitle 属性导致的。当设置 windowActionBar 为 true 时,系统会默认使用 ActionBar。而如果同时设置 windowNoTitle 为 true,则会尝试隐藏标题栏,但 ActionBar 仍然存在,导致冲突。
解决方法
- 打开
res/values/styles.xml文件。 - 找到
AppTheme主题,将windowActionBar属性设置为 false,并注释掉windowNoTitle属性,如下所示:
<style name='AppTheme' parent='Theme.AppCompat.Light.DarkActionBar'>
<!-- Customize your theme here. -->
<!--<item name='windowNoTitle'>true</item>-->
<item name='windowActionBar'>false</item>
</style>
- 重新运行应用程序,错误应该会解决。
代码示例
MainActivity.kt
package com.example.materialtest
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import com.example.materialtest.databinding.ActivityMainBinding
class MainActivity : AppCompatActivity() {
private lateinit var binding: ActivityMainBinding
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
binding = ActivityMainBinding.inflate(layoutInflater)
setContentView(binding.root)
setSupportActionBar(binding.toolbar)
}
}
activity_main.xml
<?xml version='1.0' encoding='utf-8'?>
<FrameLayout xmlns:android='http://schemas.android.com/apk/res/android'
xmlns:app='http://schemas.android.com/apk/res-auto'
android:orientation='vertical'
xmlns:tools='http://schemas.android.com/tools'
android:layout_width='match_parent'
android:layout_height='match_parent'
tools:context='.MainActivity'>
<!-- 定义Toolbar控件
这里我们使用了android:theme属性,将Toolbar的主题指定成了ThemeOverlay.AppCompat.Dark.ActionBar
使用了app:popupTheme属性,单独将弹出的菜单项指定成了浅色主题-->
<androidx.appcompat.widget.Toolbar
android:id='@+id/toolbar'
android:layout_width='match_parent'
android:layout_height='?attr/actionBarSize'
android:background='@color/colorPrimary'
android:theme='@style/ThemeOverlay.AppCompat.Dark.ActionBar'
app:popupTheme='@style/ThemeOverlay.AppCompat.Light' />
</FrameLayout>
总结
通过以上步骤,您可以轻松解决 Android 应用中使用 Toolbar 控件时遇到的 'This Activity already has an action bar supplied by the window decor' 错误,并成功使用 Toolbar 控件。
希望本文能够帮助您解决问题。如果您有任何疑问,请随时在评论区留言。
原文地址: https://www.cveoy.top/t/topic/qwxD 著作权归作者所有。请勿转载和采集!