Skip to content

Instantly share code, notes, and snippets.

@miguelhincapie
Created April 6, 2020 01:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save miguelhincapie/4223142215a99c90681144a6e5561f23 to your computer and use it in GitHub Desktop.
Save miguelhincapie/4223142215a99c90681144a6e5561f23 to your computer and use it in GitHub Desktop.
Class designated to process TalkBack accessibility key events using delegate pattern.
const val KEYCODE_CHANGE_ACCESSIBILITY_STATE = KeyEvent.KEYCODE_S
class KeyEventHandler @Inject constructor() {
/**
* Contains all possible accessibility actions available for the current Activity.
*/
private var keyEventActionMap = SparseArrayCompat<KeyEventAction>()
fun addKeyEventDelegate(keyEventDelegateImpl: BaseKeyEventDelegate) {
keyEventActionMap.putAll(keyEventDelegateImpl.keyEventActionMap)
}
/**
* If an external keyboard or accessibility device is being used, probably there is a key
* associated to turn ON/OFF TalkBack service.
* @return <code>true</code> if the key to turn ON/OFF TalkBack was pressed, <code>false</code>
* in other case.
*/
fun switchAccessibilityKeyPressed(event: KeyEvent) =
KEYCODE_CHANGE_ACCESSIBILITY_STATE == event.keyCode && KeyEvent.ACTION_DOWN == event.action
fun handleEvent(event: KeyEvent, viewWR: WeakReference<View>): Boolean? {
return viewWR.get()?.let {
with(createKey(it.id, event.keyCode, event.action)) {
keyEventActionMap.get(this)?.invoke(it)
}
}
}
}
/**
* Allows create a unique [Int] value associated to elements given in parameters.
*
* Note: Prime numbers are chosen to best distribute data among hash buckets, so that's why we are using
* 31 as value.
*/
fun createKey(focusedViewId: Int, keyCode: Int, action: Int): Int {
var result = focusedViewId
result = 31 * result + keyCode.hashCode()
result = 31 * result + action.hashCode()
return result
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment