Getting toolbar in fragment

I customize the toolbar in my main activity, and when I go inside the fragment, I want to add a slider to it. If I had 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 with

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

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

I'm not sure if this is the best look at this, but I don’t think I can use Spinner in the layout because most of my snippets don’t use it, they just set the title on the toolbar. But at the same time, it would be great if I could define the toolbar once in the main action, and not repeat it for each fragment.

+5
source share
4 answers

Another way to get the same answer from Ellitz is, inside the fragment, directly access the toolbar (or any other view inside the operation):

 Toolbar toolbar = (Toolbar) getActivity().findViewById(R.id.toolbar); 
+24
source

you can get it with

 Toolbar refTool = ((NameOfClass)getActivity()).toolbar; 

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

+5
source

In the main menu of the toolbar https://developer.android.com/reference/android/widget/Toolbar.html read here so that there is nothing respect in the toolbar and action bar. therefore, if you want to add a view to the toolbar before it is installed in the Actionbar, then toolbar.addView(your view); will be fine, but after applying it to setactionbar(toolbar) or setSupportActionbar(toolbar) you can set the view to the action bar.

ex. ((ActionBarActivity) getActivity ()). GetSupportActionBar (). SetView (your view)

Here it is...

0
source

I would like to add casting to what Budius said.

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

is the right way to do this. Because

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

returns a view. This will give you an error, and you must point it to the Toolbar .

0
source

All Articles