【问题标题】:Create context menu on menu item click在菜单项单击时创建上下文菜单
【发布时间】:2017-05-13 07:37:52
【问题描述】:

我的情况很奇怪,我试图到处搜索,但没有找到任何有用的东西。可能是我遵循糟糕的设计。但这是我的情况:

我的应用程序中有AppBar,我在应用程序栏上添加了ActionButton,我们通常这样做。现在我想在用户单击应用栏的任何操作按钮时显示上下文菜单。

例如:如果我在应用栏上有设置按钮,并且如果用户单击该按钮,那么我想显示具有多个选项的上下文菜单。 我知道如何创建上下文菜单和处理上下文菜单项单击,但我不知道如何从操作按钮单击转移控制,从而导致显示ContextMenu

这是我的代码:

//inflating context menu which will display when user clicks app bar button example like setting

    public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) {
        super.onCreateContextMenu(menu, v, menuInfo);
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(R.menu.context_menu_sort, menu);
    }

//handling context menu item clicks
    @Override
    public boolean onContextItemSelected(MenuItem item) {
        return super.onContextItemSelected(item);
    }

但我不确定如何处理会显示上下文菜单的应用栏按钮点击:

//Below code is to handle app bar item clicks

    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }

        //handling the menu clicks on menu.xml
        switch (id){
//on below action_add click i want to display context menu
            case R.id.action_add:
//not sure what to code here
                break;
}

感谢您的帮助

【问题讨论】:

    标签: android toolbar appbar android-contextmenu


    【解决方案1】:

    如果我的理解正确,您想显示子菜单吗? 然后你需要在你的R.menu.context_menu_sort 中添加一个menu 标签。

    像这样:

    <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:id="@+id/file"
              android:title="@string/file" >
            <!-- "file" submenu -->
            <menu>
                <item android:id="@+id/create_new"
                      android:title="@string/create_new" />
                <item android:id="@+id/open"
                      android:title="@string/open" />
            </menu>
        </item>
    </menu>
    

    欲了解更多信息,请参阅https://developer.android.com/guide/topics/ui/menus.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2010-09-21
      • 2016-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-07-27
      • 1970-01-01
      相关资源
      最近更新 更多