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.
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);
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With