Home > Software engineering >  How to set different Title in toolbar for different Fragment?
How to set different Title in toolbar for different Fragment?

Time:01-13

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

CodePudding user response:

Create a function that takes care of both the title as well as the fragment transaction something life this

Function to change title and transaction

private void displayFragment(int position) {
    // update the main content by replacing fragments
    Fragment fragment = null;
    String title = "";
    switch (position) {
    case 0:
        fragment = new Home();
        title = "Home";
        break;
    case 1:
        fragment = new Login();
        title = "Login";
        break;
    case 2:
        fragment = new RestorePass();
        title = "Restore Password";
        break;

    default:
        break;
    }

    // update selected fragment and title
    if (fragment != null) {
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.frame_container, fragment).commit(); //replace with id of your frame container
        getSupportActionBar().setTitle(title);
        // change icon to arrow drawable
        getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_arrow);
    }
}

Now let us suppose you want to go to the 1st fragment. Just type displayFragment(0); This way your title would be Home and the transaction will take place as well. Remove the explicit set title from your code

CodePudding user response:

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
    }
}
  •  Tags:  
  • Related