Issue
How to handle three presses on volume up button in my activity ?
override fun dispatchKeyEvent(event: KeyEvent?): Boolean {
val action = event!!.action
return when (val keyCode = event.keyCode) {
//handle press on volume up button
KeyEvent.KEYCODE_VOLUME_UP -> {
if (action == KeyEvent.ACTION_UP) {
}
true
}
else -> super.dispatchKeyEvent(event)
}
}
Solution
You could encapsulate the handling of multi-taps in a helper class like this. This class accepts each tap of the button when you call submitTap()
, and if the specified number of taps happen within a certain amount of time (withinMillis
), then it fires the onMultiTap
callback. If it has been too long since the first of the taps it has been counting, it resets its time and counts the latest tap as the first of a new count.
class MultiTapHandler(
val multiTapCount: Int,
val withinMillis: Long,
var onMultiTap: () -> Unit
) {
init {
require(multiTapCount > 1) { "Must have multiTapCount of at least 2." }
}
private var firstInputTime = 0L
private var count = 0
fun submitTap() {
val time = System.currentTimeMillis()
when {
count == 0 || time - firstInputTime > withinMillis -> {
count = 1
firstInputTime = time
}
++count == multiTapCount -> {
count = 0
onMultiTap()
}
}
}
}
So to use it in your code, where you want to do something when there is a triple-tap of the volume button, you would store it in a property with a multiTapCount
of 3. You can experiment with values of withinMillis
to find what feels right.
private val tripleVolumeUpHandler = MultiTapHandler(3, 500L) {
Log.d(TAG, "Just got triple tap on volume up button!")
}
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
val action = event.action
return when (val keyCode = event.keyCode) {
KeyEvent.KEYCODE_VOLUME_UP -> {
if (action == KeyEvent.ACTION_UP) {
tripleVolumeUpHandler.submitTap()
}
true
}
else -> super.dispatchKeyEvent(event)
}
}
Edit: If you want to handle single, double, and triple taps of the button, you can create a second instance like this:
private val doubleVolumeUpHandler = MultiTapHandler(2, 250L) {
Log.d(TAG, "Just got double tap on volume up button!")
}
private val tripleVolumeUpHandler = MultiTapHandler(3, 500L) {
Log.d(TAG, "Just got triple tap on volume up button!")
}
override fun dispatchKeyEvent(event: KeyEvent): Boolean {
val action = event.action
return when (val keyCode = event.keyCode) {
KeyEvent.KEYCODE_VOLUME_UP -> {
if (action == KeyEvent.ACTION_UP) {
doSingleTapAction()
doubleVolumeUpHandler.submitTap()
tripleVolumeUpHandler.submitTap()
}
true
}
else -> super.dispatchKeyEvent(event)
}
}
Answered By - Tenfour04
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.