I am implementing accessibility in my app, including keyboard navigation. Currently, there is some selectable text which shows the context menu when the user long clicks/long presses the text.
When using an external keyboard to navigate, there is no way to open this context menu that I've found.
I want to show the context menu when the TextView is focused and the Enter or Space key is pressed. This is what I have been trying:
textView.setOnKeyListener { view, keyCode, event ->
if (event.action == KeyEvent.ACTION_DOWN) {
if ((keyCode == KeyEvent.KEYCODE_SPACE || keyCode == KeyEvent.KEYCODE_ENTER)) {
performLongClick()
true
} else {
super.onKeyDown(keyCode, event)
}
} else {
super.onKeyUp(keyCode, event)
}
}
I've also tried the onKeyListener with view.performContextClick() and view.showContextMenu(), but none of these produce the context menu.
The only thing that has worked for me is creating a custom context menu, and then calling it using the above code.
override fun onCreateContextMenu(
menu: ContextMenu,
view: View,
menuInfo: ContextMenu.ContextMenuInfo?
) {
super.onCreateContextMenu(menu, view, menuInfo)
// add menu items
menu.add(0, view.id, 0, "Copy")
menu.add(0, view.id, 0, "Share")
}
override fun onContextItemSelected(item: MenuItem): Boolean {
when {
item.title === "Copy" -> {
clip = ClipData.newPlainText("copy", text)
clipBoard?.setPrimaryClip(clip)
}
item.title === "Share" -> {
val sharingIntent = Intent(Intent.ACTION_SEND)
sharingIntent.type = "text/plain"
sharingIntent.putExtra(Intent.EXTRA_TEXT, text)
startActivity(Intent.createChooser(sharingIntent, "Share"))
}
}
return true
}
Ideally I would prefer to show the default context menu. Is there any way to show the context menu using the keyboard without manually creating a context menu?