Toolbar: the overflow menu button is always displayed

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

What I need : I want the overflow menu button to appear only when the device does not have a 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 action (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 will be appreciated!

+5
source share
3 answers

I found a solution to my problem:

1- do not call setSupportActionBar(mToolbar); , but use the toolbar directly

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

3- if the device has an i menu button, return true to onCreateOptionsMenu , otherwise I will inflate the menu on the toolbar

+2
source

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

 @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); } 
+2
source

It works great (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 usual in onCreateOptionsMenu.

0
source

Source: https://habr.com/ru/post/1208593/


All Articles