Android Toolbar 使用指南:解决 "Activity 已有 ActionBar" 报错
Android Toolbar 使用指南:解决 'Activity 已有 ActionBar' 报错
在 Android 开发中,使用 Toolbar 替代 ActionBar 是一种常见的做法。但是,在某些情况下,您可能会遇到以下错误信息:
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.
这个错误提示告诉我们:该 Activity 已经有一个由窗口装饰提供的 ActionBar。因此,我们需要告诉应用程序不使用窗口装饰提供的 ActionBar,而是使用 Toolbar。
解决方法
您可以尝试以下两种方法解决这个问题:
1. 在 styles.xml 文件中设置 windowActionBar 属性
在 styles.xml 文件中的 AppTheme 主题中将 windowActionBar 属性设置为 false,以告诉应用程序不使用窗口装饰提供的 ActionBar,而使用 Toolbar。
<resources>
<string name="app_name">MaterialTest</string>
<!-- Base application theme. -->
<style name="AppTheme" 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>
<item name="windowActionBar">false</item>
</style>
</resources>
2. 在 MainActivity 中使用 supportActionBar 属性设置 Toolbar
在 MainActivity 的 onCreate 方法中,使用 supportActionBar 属性将 Toolbar 设置为 ActionBar。首先需要将 MainActivity 继承自 AppCompatActivity,然后在 setSupportActionBar 之前调用 supportActionBar。
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)
supportActionBar?.setDisplayHomeAsUpEnabled(true)
}
}
总结
通过这两种方法,您应该能够解决 "Activity 已有 ActionBar" 的问题。如果仍然有问题,请检查其他地方是否有使用 ActionBar 的代码,可能需要将其删除或注释掉。
希望本文能帮助您解决 Toolbar 使用中的问题!
原文地址: https://www.cveoy.top/t/topic/qwtf 著作权归作者所有。请勿转载和采集!