首页 > 解决方案 > Android Studio 中的顶部导航栏标题替换

问题描述

我知道这是一个常见的问题,但我尝试了不同的方法来替换导航栏的标题,但它对我不起作用。每当我使用工具栏时,我只想替换导航栏的标题。因为我的 app_name 的默认标题是 OldTitle。

在此处输入图像描述

我已经尝试过但它不起作用

android:label="new title" 

我也试过了,但它使我的应用程序崩溃

getSupportActionBar().setTitle("New Title");

错误 :

Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.setTitle(java.lang.CharSequence)' on a null object reference

menu在工具栏布局中使用了文件夹和显示

我的主菜单

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:android="http://schemas.android.com/apk/res/android">
<item
    android:id="@+id/app_bar_search"
    android:icon="@drawable/ic_search_black_24dp"
    android:title="Search"
    android:label="My new title"
    app:actionViewClass="android.widget.SearchView"
    app:showAsAction="always" />
</menu>

活动主.xml

<com.google.android.material.appbar.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content">

    <androidx.appcompat.widget.Toolbar
        android:id="@+id/mainToolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"
        android:backgroundTint="@android:color/white"
        app:liftOnScroll="true"/>

</com.google.android.material.appbar.AppBarLayout>

我的活动课

    Toolbar mToolbars = findViewById(R.id.mainToolbar);
    setSupportActionBar(mToolbars);

标签: javaandroid

解决方案


试试下面的代码

爪哇:

Toolbar mToolbars = findViewById(R.id.mainToolbar);
setSupportActionBar(mToolbars);
getSupportActionBar().setTitle("New Title");

科特林:

  val mToolbars: Toolbar = findViewById(R.id.mainToolbar)
  setSupportActionBar(mToolbars)
  supportActionBar!!.setTitle("New Title")

推荐阅读