在片段中获取工具栏 [英] Getting Toolbar in Fragment

查看:104
本文介绍了在片段中获取工具栏的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在主要活动中设置了一个工具栏,当我进入一个片段时,我想在其上添加一个滑块.如果我有权访问工具栏对象,则只需执行以下操作:

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

但是如果我使用

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

我没有任何addView()方法.所以我的问题是,如果工具栏本身是在Activity中创建的,如何将视图片段添加到工具栏.

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.

我不确定这是否是解决此问题的最佳方法,但是我认为我无法在布局中定义Spinner,因为我的大多数片段都不使用它,它们只是设置了工具栏的标题.但是同时,如果我可以在主活动中定义一次工具栏,而不是为每个片段重做一次,那将是很棒的事情.

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.

推荐答案

从Ellitz答案中实现相同目的的另一种方法是,在片段内部直接访问工具栏(或活动内部的任何其他视图):

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

这篇关于在片段中获取工具栏的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆