-1

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()

2 Answers2

0

Change the above code like this :

btnamb.setOnClickListener{
    var mediaPlayer = MediaPlayer.create(context, R.raw.ambulance)
    mediaPlayer.start()
}
Ankit Gupta
  • 244
  • 1
  • 5
  • 17
0

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

Robin Chien
  • 13
  • 1
  • 4