Karim Aly
Karim Aly

Reputation: 569

Toolbar : overflow menu button always showing

Problem: after updating the support library and using Toolbars, the overflow menu button is always showing on devices with and without hardware menu button

What I Need: I want the overflow menu button to show only when the device has no hardware menu button

menu.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto" >

<item
    android:id="@+id/action_settings"
    app:showAsAction="never"
    android:title="@string/action_settings"/>

<item
    android:id="@+id/import_data"
    app:showAsAction="never"
    android:title="@string/import_data"/>

in the activity (ActionBarActivity)

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main, menu);
    return true;
}

and in onCreate : setSupportActionBar(mToolbar);

Help would be appreciated!

Upvotes: 5

Views: 2913

Answers (3)

Thuo
Thuo

Reputation: 46

You can change the behavior of the hardware menu button when it is present to show/hide the toolbar overflow menu. To do so, override the onKeyUp method of Activity.

@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_MENU) {
        if (mToolbar.isOverflowMenuShowing()) {
            mToolbar.hideOverflowMenu();
        } else {
            mToolbar.showOverflowMenu();
        }
        return true;
    }
    return super.onKeyUp(keyCode, event);
}

Upvotes: 2

Leebeedev
Leebeedev

Reputation: 2146

It works fine (at least for me).

In the onCreate method of your activity do:

    boolean hasHarwareMenu = ViewConfigurationCompat.hasPermanentMenuKey(ViewConfiguration.get(getApplicationContext()));
    if (!hasHarwareMenu) setSupportActionBar(toolbar);

And inflate your menu.xml as normal in the onCreateOptionsMenu.

Upvotes: 0

Karim Aly
Karim Aly

Reputation: 569

I found the solution to my problem:

1- don't call setSupportActionBar(mToolbar); any more, instead use Toolbar directly

2- check if device has a hardware menu button by calling ViewConfigurationCompat.hasPermanentMenuKey(ViewConfiguration.get(getApplicationContext())); :

3- if device has menu button i return true on in onCreateOptionsMenu, else i inflate the menu in the Toolbar

Upvotes: 2

Related Questions