How to set title in app bar with Navigation Architecture Component

It’s actually because of:

android:label="fragment_main"

Which you have set in the xml.

So what is the proper way to show the title for Fragments using
Navigation Component?

setTitle() works at this point. But, because you set label for those Fragments, it might show the label again when recreating the Activity. The solution will probably be deleting android:label and then do your things with code:

((AppCompatActivity) getActivity()).getSupportActionBar().setTitle("your title");

Or:

((AppCompatActivity) getActivity()).getSupportActionBar().setSubtitle("your subtitle");

In onCreateView().


Found a workaround:

interface TempToolbarTitleListener {
    fun updateTitle(title: String)
}

class MainActivity : AppCompatActivity(), TempToolbarTitleListener {

    ...

    override fun updateTitle(title: String) {
        binding.toolbar.title = title
    }
}

Then:

(activity as TempToolbarTitleListener).updateTitle("custom title")

Check this out too:Dynamic ActionBar title from a Fragment using AndroidX Navigation

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)