Created
April 6, 2020 01:10
-
-
Save miguelhincapie/4223142215a99c90681144a6e5561f23 to your computer and use it in GitHub Desktop.
Class designated to process TalkBack accessibility key events using delegate pattern.
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
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