Issue
I'm new to Jetpack Compose, and I'm creating app that will use volume buttons to say, if user presses volume up button text for example must be true, if user presses volume down text must be set to false
Here, I found one not full answer to use onKeyEvent
method. Because of answer was not full I tried to make it myself because on the internet there were no answers, but it didnt helped me. When I press buttons they aren't tracking.Below is part of my code that I wrote:
Image(
painter = painterResource(id = R.drawable.white_imprint),
contentDescription = null,
modifier = Modifier
.alpha(imageVisible)
.onKeyEvent {
var returnExsp: Boolean = false
if (it.key.keyCode.toInt() == KeyEvent.KEYCODE_VOLUME_DOWN) {//it is what i tried to do
exspresion = false //it is part of another code
volumeBtnPressed = true //it is part of another code
returnExsp = true
println("Volume down") //how i checked tracking of buttons
Log.d("@@@@", "Volume down: ") //how i checked tracking of buttons
return@onKeyEvent true
} else if (it.nativeKeyEvent.keyCode == KeyEvent.KEYCODE_VOLUME_UP) {
exspresion = true
volumeBtnPressed = true
returnExsp = true
Log.d("@@@@", "Volume up: ")
return@onKeyEvent true
}
return@onKeyEvent returnExsp
Maybe I made some simple mistakes, can anyone help me please?
Solution
I think you can use this code
@Composable
fun VolumeButtonsHandler(
onVolumeUp: () -> Unit,
onVolumeDown: () -> Unit
) {
val context = LocalContext.current
val view = LocalView.current
DisposableEffect(context) {
val keyEventDispatcher = ViewCompat.OnUnhandledKeyEventListenerCompat { _, event ->
when (event.keyCode) {
KeyEvent.KEYCODE_VOLUME_UP -> {
onVolumeUp()
true
}
KeyEvent.KEYCODE_VOLUME_DOWN -> {
onVolumeDown()
true
}
else -> {
false
}
}
}
ViewCompat.addOnUnhandledKeyEventListener(view, keyEventDispatcher)
onDispose {
ViewCompat.removeOnUnhandledKeyEventListener(view, keyEventDispatcher)
}
}
}
Answered By - hnxtay
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.