Skip to content Skip to sidebar Skip to footer

Getting Toolbar In Fragment

I set up a toolbar in my main activity and when I go inside a fragment, I want to add a slider on it. If I had had the access to the Toolbar object, I would simply do: Toolbar tool

Solution 1:

Another way of achieving the same thing from Ellitz answer, inside the fragment access the toolbar (or any other view inside activity) directly:

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

Solution 2:

you can get it using

ToolbarrefTool= ((NameOfClass)getActivity()).toolbar;

or, create an instance of your MainActivity, then, override onAttach(Activity activity) and assign your instance object of MainActivity to the activity in onAttach()

Solution 3:

See toolbar main purpose is https://developer.android.com/reference/android/widget/Toolbar.html read here so there are nothing deference in toolbar and actionbar. so if you want to add view to toolbar before it set to Actionbar then toolbar.addView(your view); is fine but after apply apply to setactionbar(toolbar) or setSupportActionbar(toolbar) you can set view to actionbar.

ex. ((ActionBarActivity) getActivity()).getSupportActionBar().setView(Your view)

Thats it...

Solution 4:

I would like to add a casting to what Budius said.

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

is the right way of doing it. Because

getActivity().findViewById(R.id.toolbar);

returns a view. This will give you error and you should cast it to Toolbar.

Post a Comment for "Getting Toolbar In Fragment"