Android Material Design Toolbar 使用教程:解决“This Activity already has an action bar”错误

本教程详细介绍了如何在Android应用中使用Material Design的Toolbar控件,并解决常见的错误“This Activity already has an action bar supplied by the window decor”,帮助开发者轻松实现自定义工具栏。

问题描述

在使用Material Design的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.

该错误信息提示当前Activity已经存在由窗口装饰提供的ActionBar,而你又尝试使用Toolbar来替代它。

解决方法

要解决这个问题,需要在styles.xml文件中,将AppThemewindowActionBar属性设置为false,并设置windowNoTitletrue,以确保应用不使用默认的ActionBar。

<resources>
    <!-- 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="windowActionBar">false</item> <!-- 设置windowActionBar为false -->
        <item name="windowNoTitle">true</item> <!-- 设置windowNoTitle为true -->
    </style>
</resources>

完整代码示例

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>

总结

通过以上步骤,你就可以成功地使用Material Design的Toolbar控件,并避免常见的错误。希望本教程对你有帮助!

Android Material Design Toolbar 使用教程:解决“This Activity already has an action bar”错误

原文地址: https://www.cveoy.top/t/topic/qws0 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录