java - 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);
解决方案
试试下面的代码
爪哇:
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")
推荐阅读
- glsl - 用于无绑定使用的 GLSL 中的 Sampler2D 纹理数组
- html - 我可以以某种方式更改要显示的表格的顺序吗?
- database - Grails 应用程序中特定表条目的详细信息
- go - 为什么 pprof heap inuse_space 小于 container_working_set_size?
- node.js - Mkcert 在 Node docker 容器上生成 rootCA,Browsersync over https 不安全
- php - 使用 fsockopen 连接到在另一个 PHP 实例中打开的监听端口
- shopify-app - Shopify 节点应用未显示应用嵌入主题设置
- javascript - 发送邮件时保留文本区域的换行符
- jsf - JSF 和 Bootstrap5
- c# - C# 从 IQueryCollection 读取数组