The fragment is one of the coolest android component. What makes it this cool is its lifecycle which is tightly coupled with the Activity containing it.
There are times when we are adding, replacing or removing fragment in/out from the activity. We need to reflect the changes in the activity also such as changing the activity’s/action bar title which is associated with each Fragment.
For Example:
There is an Activity called MainActivity which contain three fragment like.
Now, MainActivity has
- Fragment One
- Fragment Two
- Fragment Three
Let say, on changing any fragment we what to change the activity’s / action bar title.
This can be done by implementing FragmentManager.OnBackStackChangedListener in the activity containing those fragments.
On overriding the onBackStackChanged method, we can easily change the title and other things as per our need.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 |
@Override public void onBackStackChanged() { try { for (Fragment fragment : getSupportFragmentManager().getFragments()) { if (fragment != null && fragment.isVisible()) { if (fragment.getTag().equals(AddNewProductSelectAttributeFragment.class.getSimpleName())) { setTitle(getString(R.string.select_attribute_and_product_type)); } else if (fragment.getTag().equals(AddSimpleProductFragment.class.getSimpleName())) { setTitle(getString(R.string.add_simple_product)); } else if (fragment.getTag().equals(AddNewProductCategoryFragment.class.getSimpleName())) { setTitle(getString(R.string.select_categories)); } else if (fragment.getTag().equals(AddCustomOptionFragment.class.getSimpleName())) { setTitle(getString(R.string.add_custom_options)); } } } } catch (Exception e) { e.printStackTrace(); } } |
That’s all from side.
Happy coding !!