如何从操作栏中的按钮打开下拉菜单

时间:2014-10-13 13:19:36

标签: android button drop-down-menu overflow

我正在为Android开发一个应用程序,它需要在操作栏中有一个按钮(溢出附近),打开一个下拉菜单作为单击溢出按钮出来的菜单。有任何想法吗?谢谢

3 个答案:

答案 0 :(得分:4)

您可以做的是通过填充相关的膨胀XML文件将一个项目添加到操作栏。 在res / menu / action_bar.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools">
    <item
        android:id="@+id/new_popup"
        android:title="A popup example"
        app:showAsAction="always" // Do not forget to put showAsAction to always so that this item will not be grouped with the overflow
        android:visible="true">
        <menu>
            // Your popup items will be inserted programmatically here by adding item.getSubMenu().add(...) (see the code below)
        </menu>
    </item>
    <item>
        // The overflow items. They all will be hidden here (you put the showAsAction to never)
        ...
    </item>
</menu>

在您的活动中,您可以对此菜单进行充气:

@Override
public boolean onCreateOptionsMenu(Menu menu)
{
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.action_bar, menu);
    return true;
}

然后,填充菜单上的项目并处理这些项目上的click事件:

@Override
    public boolean onOptionsItemSelected(MenuItem item) {
int id = item.getItemId();
if (id == R.id.new_popup)
{
    item.getSubMenu().add(0, itemId, order, "your text").setIcon(your icon).setOnMenuItemClickListener(new OnMenuItemClickListener() {
 // Handle this item click event
}
    // Add more items!
}

答案 1 :(得分:1)

enter image description here

&#34;加&#34;操作栏中的按钮需要通过单击溢出按钮打开菜单。最终我需要两个菜单。

答案 2 :(得分:0)

您可以在操作栏中使用下拉菜单导航来执行此操作,此处example也会看到此example,希望这会有所帮助:)

相关问题