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

dzi*_*kyy 33 android android-menu

我想在我的应用的右上角添加一个菜单按钮,而不使用操作栏,就像在下面的屏幕截图中的Google Fit应用中一样.谁能帮我?

没有操作栏的菜单按钮

M-Y*_*M-Y 50

您可以简单地使用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();
}
Run Code Online (Sandbox Code Playgroud)

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

  • 如果您希望它位于屏幕的右侧(默认情况下显示在左侧),请在充气之前使用“popup.gravity = Gravity.END” (2认同)

Eug*_*e H 17

添加工具栏布局并使其透明.这是将菜单项添加到布局的最佳解决方案,同时给出外观没有操作栏/工具栏.

布局

<?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>
Run Code Online (Sandbox Code Playgroud)

主题

<resources>
    <!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <!-- Customize your theme here. -->
    </style>
</resources>
Run Code Online (Sandbox Code Playgroud)

充气菜单,设置标题,菜单点击监听器的示例.

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;
    }
});
Run Code Online (Sandbox Code Playgroud)

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


Aas*_*ish 6

<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" />
Run Code Online (Sandbox Code Playgroud)

在要显示此菜单的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;
    }
}
Run Code Online (Sandbox Code Playgroud)

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