Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowTitleEnabled(false);


Spinner mNavigationSpinner = new SpinnerTrigger(getSupportActionBar().getThemedContext());
toolbar.addView(mNavigationSpinner);

But if I get it using

((ActionBarActivity) getActivity()).getSupportActionBar()

I don't have any addView() method. So my question is, how can I add a view to the Toolbar in fragment if the Toolbar itself was created in an Activity.

I'm not sure if this is the best view of going about this, but I don't think I can have the Spinner in defined in the layout, because most of my fragments don't use it, they simply set a title to the toolbar. But at the same time, it would be great if I could define the toolbar once in the main activity and not redo it for every fragment.

like image 599
Limon Avatar asked Jul 13 '15 10:07

Limon


2 Answers

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

Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar);
like image 88
Budius Avatar answered Sep 18 '22 14:09

Budius


you can get it using

Toolbar refTool = ((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()

like image 20
Elltz Avatar answered Sep 19 '22 14:09

Elltz