Skip to content

Commit fb26da6

Browse files
Material Design Teamhunterstich
authored andcommitted
[Menu][A11y] Fix context menu keyboard controls in Menu demo
Previously, pressing Enter on the context menu TextView in the menu demo would incorrectly open the menu. Additionally, pressing Ctrl+Enter would open the menu as a dialog, inconsistent with the floating menu style seen on long-press. This change updates the OnKeyListener to: Ignore Enter/DPAD_CENTER/Space key presses unless Ctrl is also held down. When Ctrl+Enter is detected on API 24+, use showContextMenu(x, y) to display the menu as a floating menu centered on the view. This aligns its appearance with the long-press behavior. On API < 24, fall back to showContextMenu(), which displays the menu as a dialog. PiperOrigin-RevId: 806198204
1 parent 98a73a6 commit fb26da6

File tree

1 file changed

+19
-4
lines changed

1 file changed

+19
-4
lines changed

catalog/java/io/material/catalog/menu/MenuMainDemoFragment.java

Lines changed: 19 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -104,10 +104,25 @@ private void setupContextMenuWithKeyboard(View view) {
104104
registerForContextMenu(view);
105105
view.setOnKeyListener(
106106
(v, keyCode, event) -> {
107-
if (event.getAction() == KeyEvent.ACTION_DOWN
108-
&& event.isCtrlPressed()
109-
&& (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_DPAD_CENTER)) {
110-
v.showContextMenu();
107+
if (event.getAction() != KeyEvent.ACTION_DOWN) {
108+
return false;
109+
}
110+
111+
if (keyCode == KeyEvent.KEYCODE_SPACE) {
112+
return true;
113+
}
114+
115+
if (keyCode == KeyEvent.KEYCODE_ENTER || keyCode == KeyEvent.KEYCODE_DPAD_CENTER) {
116+
if (event.isCtrlPressed()) {
117+
// Use showContextMenu(x, y) to show the context menu as a floating menu
118+
// on newer Android versions, similar to long-press. Fall back to
119+
// showContextMenu() on older versions, which will appear as a dialog.
120+
if (VERSION.SDK_INT >= VERSION_CODES.N) {
121+
v.showContextMenu(v.getWidth() / 2f, v.getHeight() / 2f);
122+
} else {
123+
v.showContextMenu();
124+
}
125+
}
111126
return true;
112127
}
113128
return false;

0 commit comments

Comments
 (0)