I'm starting with JetPack Compose and I want to make an Audio player, everything works fine, only in one Box
I have an image of the song cover and on top I have a play button, clicking on the image plays and pauses, but it doesn't work. What I want to know, if you help me, is how when you click on the play image, it changes to the pause image
Image(
painter = painterResource(id = R.drawable.play),
contentDescription = "Play",
modifier = Modifier
.clickable(onClick = {
if (mp?.isPlaying == true) {
mp?.pause()
} else {
mp?.play()
}
})
.align(Alignment.Center)
.width(50.dp)
.height(50.dp)
)//Image
Jetpack Compose is based on the declarative UI paradigm. In this paradigm, the UI is immutable and so you can't do something like change an image. Instead, each change in your app's state produces a new UI. In other words, what you must modify is not the image but the state.
To do this, the first thing you need is to create a state that in your case could be called
isPlaying
This creates a mutable state with the initial value
false
(I'm assuming initially the song won't be playing). It is also making use of delegates so that the state is updated automatically when you change the value of the variable. For more details read the documentation .The next step is to define which image to generate in each state
Finally you create the image that corresponds to a
onClick
that updates the value ofisPlaying
When a state changes, what compose calls recomposition occurs , then all that code is executed again, generating a new image in the same place where the previous one was. This produces the same result you wanted although it is very different conceptually. For a better explanation watch this video .