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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With