Created
December 8, 2014 19:28
-
-
Save easyaspi314/bd217a40e1a521bf1083 to your computer and use it in GitHub Desktop.
How to get the Menu key working in AppCompat
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package foo.bar; | |
import android.support.v7.app.ActionBarActivity; | |
import android.support.v7.widget.Toolbar; | |
import android.os.Bundle; | |
import android.view.KeyEvent; | |
import android.view.Menu; | |
public class FooActivity extends ActionBarActivity { | |
private Toolbar toolbar; | |
@Override | |
public void onCreate(Bundle icicle){ | |
setContentView(R.layout.foo); | |
toolbar = (Toolbar) findViewById(R.id.toolbar); | |
if (toolbar !=null) { | |
setSupportActionBar(toolbar); | |
} | |
} | |
@Override | |
public boolean onCreateOptionsMenu(Menu menu) { | |
getMenuInflater().inflate(R.menu.main, menu); | |
return true; | |
} | |
public boolean onKeyUp(int keyCode, KeyEvent event) { | |
// Menu key was pressed. | |
if (keyCode == KeyEvent.KEYCODE_MENU) { | |
toolbar = (Toolbar) findViewById(R.id.toolbar); | |
if (toolbar.isOverflowMenuShowing()) { | |
// Overflow is showing, hide the menu. | |
toolbar.dismissPopupMenus(); | |
} else { | |
// Overflow is hidden, show menu. | |
toolbar.showOverflowMenu(); | |
} | |
return true; | |
} | |
return super.onKeyUp(keyCode, event); | |
} | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?xml version="1.0" encoding="utf-8"?> | |
<menu xmlns:android="http://schemas.android.com/apk/res/android" | |
xmlns:appcompat="http://schemas.android.com/apk/res-auto"> | |
<item android:id="@+id/foo" android:title="@string/foo" android:icon="@drawable/ic_foo" appcompat:showAsAction="always" /> | |
<item android:id="@+id/bar" android:title="@string/bar" appcompat:showAsAction="never" /> | |
</menu> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment