Question

Hi i have an app with 2 buttons (play and pause), there is a way to put Play/Pause in the same button and other button with Restart? Because i tried some codes but i get errors(see commentaries)

Here my code:

import android.app.Activity;
import android.media.MediaPlayer;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;


public class MainActivity extends Activity {


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    final MediaPlayer mp = MediaPlayer.create(this, R.raw.sound);

     Button Play = (Button) findViewById(R.id.button1);
        Play.setOnClickListener(new OnClickListener(){


        @Override
        public void onClick(View v) {
            mp.start();
        }});


        final Button button2 = (Button) findViewById(R.id.button2);
        button2.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {

             mp.stop();
             //mp.reset();

            }
        });

}
}

Thanks

Was it helpful?

Solution

Yes you can do both the operation in same button for that do it like below.

button1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View arg0) {
                if (mp.isPlaying()) {
                    if (mp != null) {
                           mp.reset();
                           mp.prepare();
                           mp.start();
                           mp.pause();
                        button1.setText("Play");
                    }
                } else {
                    if (mp != null) {
                        mp.start();
                        button2.setText("Pause");
                    }
                }
            }
        });

Declare mp as a private MediaPlayer mp = new MediaPlayer(this, R.raw.sound);

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top