如何在片段中设置工具栏的菜单

时间:2017-07-01 11:01:17

标签: android toolbar android-toolbar

我有一个简单的布局,其中一个主要<html> <body> <p>&#128286;</p> </body> </script> </html>,一个Activity和一个带有4个按钮的ViewPager。点击每个按钮只会更改ViewPager上的当前项目,该项目会加载正确的BottomNavigationView

每个片段都有自己的Fragment,我的目标是让每个片段在工具栏上显示不同的菜单项。我已经尝试了几种方法但是还没有能够在工具栏中显示任何菜单项。这是我的代码:

Fragment.java

android.support.v7.widget.Toolbar

menu.xml文件

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_category, container, false);

        Toolbar toolbar = (Toolbar) view.findViewById(R.id.main_toolbar);
        toolbar.setTitle("Fragment title");

        AppCompatActivity activity = (AppCompatActivity) getActivity();
        activity.setSupportActionBar(toolbar);
        setHasOptionsMenu(true);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

活动本身没有与菜单相关的代码。我缺少什么想法?

2 个答案:

答案 0 :(得分:1)

@Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_category, container, false);
        Toolbar toolbar = (Toolbar) getactivity().findViewById(R.id.main_toolbar);
        ((ActionBarActivity)getActivity()).setSupportActionBar(mToolbar);
        setHasOptionsMenu(true);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }

答案 1 :(得分:0)

尝试添加行

def check_output(*popenargs, timeout=None, **kwargs):
    if 'stdout' in kwargs:
        raise ValueError('stdout argument not allowed, it will be overridden.')

    if 'input' in kwargs and kwargs['input'] is None:
        # Explicitly passing input=None was previously equivalent to passing an
        # empty string. That is maintained here for backwards compatibility.
        kwargs['input'] = '' if kwargs.get('universal_newlines', False) else b''

    return run(*popenargs, stdout=PIPE, timeout=timeout, check=True,
**kwargs).stdout
片段的AppCompatActivity activity = (AppCompatActivity) getActivity(); activity.setSupportActionBar(toolbar);

中的