I have three fragments A,B and c in one activity, activity has a toolbar with test view title.
Now as I navigate from fragment to fragment I want to change the text of text view depending on which fragment is shown.
For this in fragment B and C I am getting the toolbar of main activity and the text view and changing its title like this:
final Toolbar toolbar = (Toolbar) ((MainActivity) getActivity()).findViewById(R.id.toolbar);
((MainActivity) getActivity()).setSupportActionBar(toolbar);
TextView title = (TextView) getActivity().findViewById(R.id.textView_Title);
title.setVisibility(View.VISIBLE);
title.setText(R.string.profile);
This works fine. But when I go back to main fragment I want to change the title again but its not getting change.
I tried to set it in onCreate method of main activity, and like this:
@Override
public void onBackPressed() {
DashboardFragment test = (DashboardFragment) getSupportFragmentManager().findFragmentByTag("DASHBOARD_FRAGMENT");
if (test != null && test.isVisible()) {
//DO STUFF
title = (TextView) findViewById(R.id.textView_Title);
title.setVisibility(View.VISIBLE);
title.setText(R.string.dashboardTitle);
}
else {
//Whatever
}
// Do nothing if the back button is disabled.
if (!mBackPressCancelled) {
if (getFragmentManager().getBackStackEntryCount() > 0) {
getFragmentManager().popBackStackImmediate();
}
else {
super.onBackPressed();
}
}
}
But with this it changes its title to main fragments title even B fragment is visible.
How can I do this. Please help. Thank you.
EDIT:
MainFragment :
fragmentManager = getSupportFragmentManager();
DashboardFragment fragment1 = new DashboardFragment();
Bundle bundle = new Bundle();
fragment1.setArguments(bundle);
fragmentManager.popBackStack(null,FragmentManager.POP_BACK_STACK_INCLUSIVE);
fragmentManager.beginTransaction().replace(R.id.frame, fragment1, "DASHBOARD_FRAGMENT").commitAllowingStateLoss();
A fragment:
fragmentManager = ((MainActivity)(mContext)).getSupportFragmentManager();
ProfileFragment fragment1 = new ProfileFragment();
Bundle bundle = new Bundle();
fragment1.setArguments(bundle);
fragmentManager.beginTransaction().add(R.id.frame, fragment1, "PROFILE_FRAGMENT").addToBackStack("B").commit();
B fragment
fragmentManager = getActivity().getSupportFragmentManager();
ProfileEditFragment fragment1 = new ProfileEditFragment();
Bundle bundle = new Bundle();
fragment1.setArguments(bundle);
fragmentManager.beginTransaction().add(R.id.frame, fragment1, "PROFILE_EDIT_FRAGMENT").addToBackStack("C").commit();