如何添加没有操作栏的菜单按钮?

How to add menu button without action bar?

我想在我的应用程序的右上角添加一个菜单按钮,但没有操作栏,就像下面屏幕截图中的 Google Fit 应用程序一样。 谁能帮帮我?

您可以简单地使用 PopupMenu,例如在单击时将以下内容添加到按钮:

public void showPopup(View v) {
    PopupMenu popup = new PopupMenu(this, v);
    MenuInflater inflater = popup.getMenuInflater();
    inflater.inflate(R.menu.actions, popup.getMenu());
    popup.show();
}

科特林

fun showPopup(v : View){
   val popup = PopupMenu(this, v)
   val inflater: MenuInflater = popup.menuInflater
   inflater.inflate(R.menu.actions, popup.menu)
   popup.setOnMenuItemClickListener { menuItem ->
      when(menuItem.itemId){
         R.id.action1-> {
             
         }
         R.id.action2-> {

         }
      }
      true
   }
   popup.show()
}

有关详细信息,请阅读 Creating a Popup Menuhttp://developer.android.com/guide/topics/ui/menus.html

我认为您不能添加没有操作栏的菜单。但是,我可以考虑两种方法。

  1. 创建与背景颜色相同的操作栏使其不显示,然后添加菜单。

  2. 只需在屏幕右上角添加一个按钮,然后将下拉菜单放入布局中即可。

或者按照@M-Y的建议使用弹出菜单

在布局中添加工具栏并使其透明。这是向布局添加菜单项同时给出没有 actionbar/toolbar 外观的最佳解决方案。

布局

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <!-- The rest of your code here -->

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:background="@android:color/transparent"/>

</RelativeLayout>

主题

<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
    </style>
</resources>

展开菜单的例子,设置标题,菜单点击监听器。

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
toolbar.setTitle("Toolbar");
toolbar.inflateMenu(R.menu.menu_main);
toolbar.setOnMenuItemClickListener(new Toolbar.OnMenuItemClickListener() {
    @Override
    public boolean onMenuItemClick(MenuItem item) {
        if (item.getItemId() == R.id.action_refresh) {

        }
        return false;
    }
});

不要将工具栏设置为操作栏。主题只是完全删除它。

<ImageButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_overflow_holo_dark"
    android:contentDescription="@string/descr_overflow_button"
    android:onClick="showPopup" />

在要显示此菜单的 xml 文件中添加以上行。

public void showMenu(View v) {

    PopupMenu popup = new PopupMenu(this, v);
    // This activity implements OnMenuItemClickListener
    popup.setOnMenuItemClickListener(this);
    popup.inflate(R.menu.actions);
    popup.show();
}

@Override
public boolean onMenuItemClick(MenuItem item) {

    switch (item.getItemId()) {
        case R.id.archive:
            archive(item);
            return true;
        case R.id.delete:
            delete(item);
            return true;
        default:
            return false;
    }
}

有关详细信息,请访问: https://developer.android.com/guide/topics/ui/menus.html