首页 > 解决方案 > 在android studio上使用工具栏的正确方法是什么?

问题描述

我正在尝试在我的 Android Studio 项目上设置操作栏。调试时,Android Studio 没有显示任何错误,但是当我运行我的应用程序时,它会停在这一行。请建议我在 Android Studio 上使用工具栏的完美方式。

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

编辑:上述代码来自我的 Activity 类文件。这是我的 XML 文件的摘录

<androidx.appcompat.widget.Toolbar
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        android:id="@+id/toolbar"
        android:background="@color/colorPrimaryDark"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:elevation="4dp"
        app:popupTheme="@style/ThemeOverlay.AppCompat.Light"/>
    <FrameLayout
        android:id="@+id/fragment_container"
        android:visibility="visible"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

标签: javaandroid-studiotoolbar

解决方案


这是使用 android 工具栏> 在 XML 文件中使用工具栏的快速方法:

 <androidx.appcompat.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@color/blue"
        >

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:gravity="center_vertical"
            >

            <ImageView
                android:id="@+id/backButton"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:src="@drawable/ic_baseline_arrow_back_24_white"
                android:layout_alignParentTop="true"
                android:layout_alignParentBottom="true"
                android:contentDescription="@string/back_button" />

            <TextView
                android:id="@+id/tag1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="@string/create_a_push_notification"
                android:textColor="@color/white"
                android:layout_toEndOf="@+id/backButton"
                android:layout_alignParentTop="true"
                android:layout_alignParentBottom="true"
                android:gravity="center_vertical"
                android:layout_marginStart="10dp"
                android:textSize="20sp"
                android:textStyle="bold"/>
        </RelativeLayout>
    </androidx.appcompat.widget.Toolbar>

这是您可以通过 id 访问任何组件的工具栏。工具栏将如下所示: 工具栏


推荐阅读