Getting Toolbar in Fragment

房东的猫 提交于 2019-12-10 14:43:47

问题


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.


回答1:


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);



回答2:


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()




回答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...




回答4:


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

Toolbar toolbar = (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.



来源:https://stackoverflow.com/questions/31380447/getting-toolbar-in-fragment

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!