1

I have one main activity and four fragments, I want to set titles for those fragments.

I use this one in all fragments ((AppCompatActivity)getActivity()).getSupportActionBar().setTitle("Fragment Title");

but when I press back button and come to the main screen, the title remain same from previous fragments.

Please help me fix this quick.

Thanks

1 Answers1

-1

I think you can do like this on your Activity. Whenever back stack change (eg: you add or remove a Fragment), check the current visible fragment and show corresponding Toolbar title.

supportFragmentManager.addOnBackStackChangedListener {
    if (supportFragmentManager.backStackEntryCount == 0) {
        return@addOnBackStackChangedListener
    }
    val visibleFragment = supportFragmentManager.fragments.last()
    when (visibleFragment) {
        is HomeFragment -> {
            supportActionBar?.title = "Home"
        }
        is SettingFragment -> {
            supportActionBar?.title = "Setting"
        }
        // handle title for another fragment
    }
}
Linh
  • 57,942
  • 23
  • 262
  • 279