Android工具栏为不同片段添加菜单项 [英] Android Toolbar Adding Menu Items for different fragments

查看:129
本文介绍了Android工具栏为不同片段添加菜单项的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个工具栏和一个导航抽屉.当我启动我的应用程序时,将创建工具栏和导航抽屉.当我单击导航抽屉中的项目时,它将启动新的片段并保持相同的工具栏.在启动特定片段时,基本上如何在菜单栏上添加菜单项,例如搜索,添加,编辑?我不希望它们在程序开始时而是动态创建的.另外,我如何能够单击这些按钮并使它们启动其他片段.我希望在一个片段中,与另一个片段中的编辑按钮相比,工具栏中的编辑按钮具有特定的作用.谢谢!

I have a toolbar as well as a navigation drawer. When I start my app, the toolbar and navigation drawer are created. When I click items in the navigation drawer, it starts new fragments and keeps the same toolbar. How do I basically add menu items to the toolbar such as search, add, edit when I start specific fragments? I don't want them at the start of the program, but created dynamically. Also, how would I be able to click these buttons and have them start other fragments. I want it so in one fragment, the edit button in the toolbar does a specific thing compared to the edit button in another fragment. Thanks!

菜单工具栏:

<?xml version="1.0" encoding="utf-8"?>
<menu
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">

<item android:id="@+id/edit"
    android:orderInCategory="1"
    android:title="Edit"
    app:showAsAction="always"
    android:icon="@drawable/pencil_icon"/>
<item android:id="@+id/add"
    android:orderInCategory="1"
    android:title="Add"
    app:showAsAction="always"
    android:icon="@drawable/plus_icon"/>

工具栏:

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/toolbar"
android:layout_width="match_parent"
android:layout_height="55dp"
android:background="#10a1ff"
android:title="Home"
/>

推荐答案

向片段添加类似的代码:

Add similar code to your fragments:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup parent, Bundle savedInstanceState)
{
    View v = inflater.inflate(R.layout.library_fragment, parent, false);
    setHasOptionsMenu(true);
    return v;
}


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

通过这种方式,您可以为片段自定义菜单.

This way you can customize the menu for your fragments.

这篇关于Android工具栏为不同片段添加菜单项的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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