Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Toolbar with Fragments

I am trying to create a viewpager that swipes through 3 different fragments each with a different toolbar. I have implemented the new toolbar in an activity before and got it to work however I am trying to get it to work with fragments

Here is the fragment code

@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {     // Inflate the layout resource that'll be returned     View rootView = inflater.inflate(R.layout.fragment_home, container, false);       mToolbar = (Toolbar) rootView.findViewById(R.id.toolbar_home);     if (mToolbar != null) {         setSupportActionBar(mToolbar);     }     mToolbar.setTitle(null);      return rootView; } 

I am extending my fragment with Fragment, however I am getting the error

Cannot resolve method setSupportActionBar 

I am not sure how to resolve this, if I remove the setSupportActionBar code will it stop working with certain devices?

like image 306
Al Hennessey Avatar asked Mar 12 '15 21:03

Al Hennessey


People also ask

Can a fragment have toolbar?

Fragment-owned app bar Though you can add a Toolbar anywhere within your fragment's view hierarchy, you should generally keep it at the top of the screen. To use the Toolbar in your fragment, provide an ID and obtain a reference to it in your fragment, as you would with any other view.

How are fragments useful in GUI?

Fragments introduce modularity and reusability into your activity's UI by allowing you to divide the UI into discrete chunks. Activities are an ideal place to put global elements around your app's user interface, such as a navigation drawer.

How do we hide the menu on toolbar in one fragment?

How do we hide the menu on toolbar in one fragment? When you click the show button to open a fragment, you can see the fragment menu items ordered before activity menu items. This is because of the menu item's android:orderInCategory attribute value. When you click the hide button to hide the fragment.


1 Answers

Fragments don't have such method setSupportActionBar(). ActionBar is a property of Activity, so to set your toolbar as the actionBar, your activity should extend from ActionBarActivity and then you can call in your Fragment:

 ((ActionBarActivity)getActivity()).setSupportActionBar(mToolbar); 

UPDATE

If you're using AppCompatActivity :

 ((AppCompatActivity)getActivity()).setSupportActionBar(mToolbar); 
like image 178
vinitius Avatar answered Oct 06 '22 13:10

vinitius