Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android change title when using back button

Tags:

android

back

My activity:

TextView title;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    Overview overview = new Overview();

    setContentView(R.layout.activity_second);
    if (savedInstanceState == null) {
        getSupportFragmentManager().beginTransaction()
                .add(R.id.mycontainer, overview)
                .commit();
    }
    Toolbar toolbar = (Toolbar) findViewById(R.id.my_toolbar);
    //Some more code

    title = (TextView) toolbar.findViewById(R.id.screentitle);
    title.setText("Overzicht");


}



@Override
public boolean onNavigationItemSelected(MenuItem item) {

    switch(item.getItemId()){
        case R.id.nav_menu_overview:
            title.setText("Overzicht");
            getSupportFragmentManager().beginTransaction().replace(R.id.mycontainer, new Overview()).addToBackStack(null)
                    .commit();

            break;
        case R.id.nav_menu_favourites:
            title.setText("Favorieten");
            getSupportFragmentManager().beginTransaction().replace(R.id.mycontainer, new Favourites()).addToBackStack(null)
                    .commit();

            break;

        case R.id.nav_menu_profile:
            title.setText("Profiel");
            getSupportFragmentManager().beginTransaction().replace(R.id.mycontainer, new Profile()).addToBackStack(null)
                    .commit();
            break;
    }

So, right now, the title gets changed if I use my menu to change fragments. However, if I use the android backbutton, the title doesn't get changed back. How can I change the title back whenever the back button is used?

like image 772
user3117628 Avatar asked Apr 08 '26 08:04

user3117628


1 Answers

You could simply override the onBackPressed method of the activity and handle the scenario.

A much better approach would be you could set the title inside the fragment onViewCreated so that way whichever fragment is on top will automatically set the tile you want to set.

eg: Setting the title inside the fragment

Toolbar toolbar= (Toolbar) getActivity().findViewById(R.id.toolbar);
toolbar.setTitle("What ever you want to set");

Also don't set the title in onNavigationItemSelected its should be used to navigate not to set the title.

like image 151
Mukesh Solanki Avatar answered Apr 10 '26 20:04

Mukesh Solanki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!