即使手机有硬件菜单按钮,如何始终显示溢出菜单(ActionBar)?

时间:2014-03-24 10:04:19

标签: java android xml menu android-actionbar

以下提到的代码已实施。请建议我如何创建"溢出菜单"即使手机有硬件菜单按钮,操作栏中的选项也会出现?

这是我目前的代码:

MainActivity.java

public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.activity_main_actions, menu);
    return super.onCreateOptionsMenu(menu);
}

activity_main_actions.xml

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

<!-- Search  -->
<item android:id="@+id/action_search"
      android:icon="@drawable/ic_action_search"
      android:title="@string/action_search"
      android:showAsAction="ifRoom"/>

<!-- Email -->
<item android:id="@+id/action_email"
      android:icon="@drawable/ic_action_email"
      android:title="@string/action_email"
      android:showAsAction="never"/>

<!-- Help -->
<item android:id="@+id/action_help"
      android:icon="@drawable/ic_action_help"
      android:title="@string/action_help"
      android:showAsAction="never"/>

<!-- attach -->
<item android:id="@+id/action_attach"
      android:icon="@drawable/ic_action_attachment"
      android:title="@string/action_attach"
      android:showAsAction="never" />

2 个答案:

答案 0 :(得分:1)

最后我得到了以下代码的答案,它是在onCreateOptionMenu()方法之后编码的......

import android.view.ViewConfiguration;

        private void getOverflowMenu(){

         try {
            ViewConfiguration config = ViewConfiguration.get(this);
            Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
            if(menuKeyField != null) {
                menuKeyField.setAccessible(true);
                menuKeyField.setBoolean(config, false);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

答案 1 :(得分:-1)

试试这个:

由于您将showAsAction属性设置为never,因此这些菜单项永远不会显示为操作视图。试试这个:

<item android:id="@+id/action_search"
      android:icon="@drawable/ic_action_search"
      android:title="@string/action_search"
      android:showAsAction="ifRoom|withText"/>

<!-- Email -->
<item android:id="@+id/action_email"
      android:icon="@drawable/ic_action_email"
      android:title="@string/action_email"
      android:showAsAction="ifRoom|withText"/>

<!-- Help -->
<item android:id="@+id/action_help"
      android:icon="@drawable/ic_action_help"
      android:title="@string/action_help"
      android:showAsAction="ifRoom|withText"/>

<!-- attach -->
<item android:id="@+id/action_attach"
      android:icon="@drawable/ic_action_attachment"
      android:title="@string/action_attach"
      android:showAsAction="ifRoom|withText"/>