How to always show overflow menu (ActionBar) even

2019-06-14 01:26发布

问题:

Following mentioned are codes implemented. Please suggest me how to create the "overflow menu" option in action bar even if a phone have the hardware menu button?

This is my current code:

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" />

回答1:

Finally i got the answer after all with the following code, it was coded after the method 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();
        }
    }


回答2:

Try this:

Since you set the showAsAction attribute to never, then these menu items will never show as action views. Try this:

<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"/>