You can easily get the Toolbar from your Fragment , and then change or modify any property of this Toolbar inside the Fragment .
To get the Toolbar from your Activity , you might consider using this.
Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
Now you need to make changes to the Toolbar in the onResume function, and then discard the changes every time you return from the Fragment function inside onStop . Otherwise, changes made to Fragment will be transferred to other fragments, as well as when switching to another Fragment from the navigation box.
But in your case, I would recommend that each Fragment should have its own Toolbar , so that it does not conflict with each other and can be changed as necessary. And yes, remove the Toolbar from the Activity .
So, add a Toolbar to your Fragment layout like this.
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="wrap_content" android:background="?attr/colorPrimaryDark"/>
Then find it in Fragment
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View view = inflater.inflate(R.layout.fragment, container, false); Toolbar toolbar = (Toolbar) view.findViewById(R.id.toolbar);
And override the onOptionsItemSelected function.
@Override public boolean onOptionsItemSelected(MenuItem item) { switch(item.getItemId()){ case android.R.id.home: getActivity().onBackPressed(); } return super.onOptionsItemSelected(item); }
source share