Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set up toolbar as actionbar in fragment

I want to set up my toolbar as an actionbar, but since your toolbar is a layoutelement it has to be in your layout. Now my layout is in my fragment.

I added the toolbar in my layout and I call it within my fragment:

//Toolbar Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar); 

It works because I can set the title and so on but now I want it to react as a actionbar because I want to have this actually. setDisplayHomeAsUpEnabled(true)

To do that I have to change the toolbar to an actionbar:

setSupportActionBar(toolbar); 

That doesn't work in my fragment ...

Can anybody help me to get my toolbar to work as an actionbar in a fragment.

like image 990
Laurenswuyts Avatar asked Nov 20 '14 01:11

Laurenswuyts


People also ask

Can a fragment have toolbar?

When using fragments, the app bar can be implemented as an ActionBar that is owned by the host activity or a toolbar within your fragment's layout. Ownership of the app bar varies depending on the needs of your app.

How do I get the activity toolbar in fragment?

getActivity()). getToolbar(); will be the right answer!! for getting the Toolbar in fragment!!

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

When you click the hide button to hide the fragment. The fragment menu items disappear from the action bar also. You can also click back menu to exit the fragment and the activity.


1 Answers

Now ActionBarActivity is deprecated so You need to cast your activity from getActivity() to AppCompatActivity first. Here's an example:

((AppCompatActivity) getActivity()).getSupportActionBar().setSubtitle(); 

The reason you have to cast it is because getActivity() returns a FragmentActivity and you need an AppCompatActivity

like image 135
Pratik Butani Avatar answered Sep 16 '22 21:09

Pratik Butani