There is a way to put Play/pause in the same button?

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

Answers


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


Need Your Help

Calculation Frame of a UILabel Subclass

ios objective-c uitableview uilabel imessage

The bottom line is that I'm trying to reproduce the UI that iMessage has.

Importing generated XML in MS Project 2013

xml xml-parsing ms-project

I am trying to create XML for MS Project 2013 and I have a problem with Tasks.