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.
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
try:
((AppCompatActivity)getActivity()).setSupportActionBar(toolbar);
ActionBar is an Activity property. If you want to set a toolbar from a given fragment as the ActionBar of the owning Activity, then get the Activity that owns the fragment (Fragment.getActivity()
) and set its ActionBar property.
Then juse use the same setDisplayHomeAsUpEnabled method you mentioned to begin with on the ActionBar after setting your toolbar as the ActionBar to get the back / up button.
You will obviously have to manage this carefully if your app has multiple fragments within that Activity.
Use
((ActionBarActivity) getActivity()).getSupportActionBar().setSubtitle("Your Title");