android - 如何在不使用 Action Bar 的情况下显示三点菜单?

标签 android android-layout

假设我的应用程序不使用 Action Bar,有谁知道当当前设备没有硬件菜单按钮时我如何显示 3 点选项菜单?我见过类似下面的代码 fragment ,但它是用于 Action Bar 的,对吗?

<!-- list_menu.xml -->
?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item android:id="@+id/menu_item_1"
        android:title="@string/menu_string_1" 
        android:showAsAction="ifRoom|withText"/>
    <item android:id="@+id/menu_item_1"
        android:title="@string/menu_string_2" 
        android:showAsAction="ifRoom|withText"/>
</menu>

onCreateOptionsMenu 中:

public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater mi = getMenuInflater();
    mi.inflate(R.menu.list_menu, menu);
    return true;
}

谢谢!

最佳答案

澄清一下:您不希望在您的应用中使用操作栏。如果设备有硬件菜单按钮,您不想显示溢出图标(三个点)。如果设备没有硬件菜单按钮,您希望显示单独的溢出,对吧?

您可以检查硬件菜单按钮

ViewConfiguration.get(getApplicationContext()).hasPermanentMenuKey();

您可以使用以下代码为该按钮设置一个监听器:

@Override
public boolean onKeyDown(int keycode, KeyEvent e) {
    switch(keycode) {
        case KeyEvent.KEYCODE_MENU:
            doSomething();
            return true;
    }

    return super.onKeyDown(keycode, e);
}

如果设备没有硬件菜单按钮也没关系,因此您可以在任何情况下插入此方法。

处理手机有按钮的情况。如果它没有硬件按钮,您必须以编程方式在 Activity 的 onCreate() 方法中添加一个。 所以你会在 onCreate() 中写这样的东西:

LinearLayout layout = (LinearLayout) findViewById(R.id.linear_layout);
if(!ViewConfiguration.get(getApplicationContext()).hasPermanentMenuKey()) {
    Button overflowButton = new Button(this);

    // Add further parameters to the button
    // Especially the position (upper right) and the icon (overflow)

    layout.addView(overflowButton );
}

溢出图标可以在这里下载: https://developer.android.com/design/downloads/index.html (它在操作栏图标包中)。

希望这有帮助:)

关于android - 如何在不使用 Action Bar 的情况下显示三点菜单?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22836255/

相关文章:

android - 在 layout.xml 中使用 '@string/value' 时找不到资源

android - 如何在 Android Studio 中排除重命名的某些术语

android - 在 android 中滚动时使用改造从 API 获取下 10 个项目的分页

android - 异步任务和处理程序 Android

android - 如何在android中为每一行设置gridlayout的背景图片?

android - 如何以编程方式使小按钮包裹小文本

android - 中心 CheckBox 可在其内部绘制

android - 在 Android 菜单中为按钮设置动画的最简单方法

android - IntelliJ IDEA 的问题 - 不兼容的类型

android - Android Studio 中的 lint 如何与 IntelliJ 检查集成?