Home > Software engineering >  How to change toolbar title with fragment back stack
How to change toolbar title with fragment back stack

Time:01-16

I have made a very simple application with multiple fragments in one activity. Also, added toolbar.

Now 4 fragments have different titles.

when I go to fragment 1 the title is Fragment 1

when I go to fragment 2 the title is Fragment 2

now come to the problem....

when I press back from fragment 2,

I came to fragment 1.

but the title in the toolbar is still Fragment 2

This is the problem I want to solve.

Please help me to fix this.

Explain me in easy steps (prefer java)

Thank you in advance.

CodePudding user response:

You could do this by using an OnBackStackChangedListener in your Activity:

supportFragmentManager.addOnBackStackChangedListener {
    val fragment = supportFragmentManager.findFragmentById(R.id.yourFragmentFrame)
    if (fragment is BaseFragment) {
        header.text = fragment.header()
    }
}

CodePudding user response:

You can use one Toolbar for each Fragment. it's an easy way to set the header.

Just you need show each Fragment full in Activity layout.

you can create one toolbar XML and include it into each Fragment XML Layout.

see the Single Activity

  •  Tags:  
  • Related