How to change ImageView source to "Pause" when music is playing in HomeScreen in Kotlin Native

How to change ImageView source to "Pause" when music is playing in HomeScreen in Kotlin Native
android
Ethan Jackson

I'm working on a widget inside the HomeScreen in a Kotlin Native app. When the user clicks on an ImageView, a music file is played using a service — this part works correctly. Now, I want the ImageView to update its image to show a "Pause" icon while the music is playing. The goal is to show a "Pause" icon when the music is playing, so the user knows they can tap it again to stop or pause the playback.

I'm sending the widget update command from inside the service. However, since the widget is supposed to display a random text, each time the widget updates, it shows a new text. As a result, the currently playing audio no longer matches the displayed text in the widget.

Answer

Setting a resource in an ImageView is trivial. First, import a resource such as a pause icon into your drawable folder. You can load a default icon by right clicking on the drawable folder in your project resources tree and select New > Vector Asset. Pick a clip art you wish and assign it a name, e.g. icon_pause_baseline24.

Then, in your activity where you receive your event from your service you can update the resource in your ImageView by calling vb.myImageView.setImageResource() (assuming you're using view binding).

That said... you should probably use an ImageButton and you should probably define the state of your music playing or paused inside your service as a MutableStateFlow. Then you can subscribe and listen to it inside your activity inside a collect block. This is much simpler than using callbacks, listeners or broadcasts.

Related Articles