I know this is a common question to ask but I tried different ways to replace the title of the navigation bar but it didn't work for me. I just want to replace the title of the navbar whenever I use toolbar. Since the default title of my app_name is OldTitle.
What I've been tried but it's not working
android:label="new title"
I tried also this but it crashes my app
getSupportActionBar().setTitle("New Title");
error :
Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.setTitle(java.lang.CharSequence)' on a null object reference
I used menu
folder and display in Tool Bar layout
my main_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>
activitymain.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>
My Activity class
Toolbar mToolbars = findViewById(R.id.mainToolbar);
setSupportActionBar(mToolbars);