1

I have a project with around 100-200 clickable views all of which have OnClickListener. I want to make them play a sound when onClick() method gets fired. I know how to play a sound with MediaPlayer, however, I don't want to write the MediaPlayer.start() in every single onClick() method.

Is it possible to have a single interface that extends from OnClickListener which will enable all the buttons to produce a sound when clicked?

After writing the question down, I realized that, no matter what, I will need to change the code in every class that has a clickable view. But still, for the sake of future buttons what would be the best way to implement this behavior?

So far I tried: I created an interface called SoundyClickListener which extends from OnClickListener. There I implemented the onClick method. But I couldn't get my head around on how to make a sound then the onClick method gets called.

amira
  • 416
  • 1
  • 7
  • 24
  • 2
    maybe I do not fully understand the question. Why cannot you write a function in a class "Utils" for example and then call that function in each method? I suppose you have to write the logic for each button anyway, right? Or each of the 200 buttons have the same logic? – AM13 Jun 22 '20 at 18:43
  • @AM13 touché. Yeah, that was a stupid question to ask. In whatever solution I get, I will need to update the whole shebang. Turns out, I needed someone to tell me this. Deleting the post. – amira Jun 23 '20 at 00:21

1 Answers1

0
Button button  = findViewById(R.id.button);    

 button.playSoundEffect(SoundEffectConstants.CLICK);

 button.setOnClickListener(new View.OnClickListener() 
    {
            @Override
            public void onClick(View v)
     {
                
            }
        });
Samer Kasseb
  • 192
  • 3
  • 10