-2

I'm new to Kotlin. I want to add "play sound on button click" event. The code works in an activity but not in a fragment.

btnamb.setOnClickListener{

            var  mediaPlayer = MediaPlayer.create(applicationContext,R.raw.ambulance)
            mediaPlayer.start()
Emre Bah
  • 1
  • 1

2 Answers2

1

Change the above code like this :

btnamb.setOnClickListener{
    var mediaPlayer = MediaPlayer.create(context, R.raw.ambulance)
    mediaPlayer.start()
}
Ankit Gupta
  • 512
  • 1
  • 6
  • 19
0

Mediaplayer in fragment needs context. So you can use activity.applicationContext or context to get activity.

Robin Chien
  • 13
  • 1
  • 4