Hiding the toolbar for only one fragment in navigation mode

Problem

I have a navigation box with different fragments. There is a default toolbar that every Fragment should use, with the exception of one Fragment that needs to collapse the Toolbar .

My question

How can I switch between toolbars for fragments?

+5
source share
2 answers

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); // Modify your Toolbar here. // ... // For example. // toolbar.setBackground(R.color.red); // Create home button AppCompatActivity activity = (AppCompatActivity) getActivity(); activity.setSupportActionBar(toolbar); activity.getSupportActionBar().setDisplayHomeAsUpEnabled(true); } 

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); } 
+3
source

It seems you want to achieve something similar.

Nothing unusual

I did work with a common toolbar. when switching to the collapse of the fragment of the toolbar, I made the toolbar transparent, and the toolbar of the fragment intercepted. The color of the toolbar remains unchanged when switching to other fragments.

This allows you to control the full layout of the toolbar layout in xml, and the logic remains in the Snippet.

Hope this helps. Refer to the associated gif.

Gist for gif

+1
source

Source: https://habr.com/ru/post/1269155/


All Articles