21

I'm having trouble figuring out how to change the text and action of a button. What I want to do is have a button with the text "play" and when clicked it will play a song and change the text to "pause". then when you click it again, it will pause the song and change the text to "play".

I know how to use the mediaplayer (the coding) and just don't know how to code the button that way:

so far I have:

final Button testButton = (Button) findViewById(R.id.button1);
testButton.setText("Play");
testButton.setOnClickListener( new View.OnClickListener() {

@Override
public void onClick (View v) {
mPlayer.start();
testButton.setText("Pause");

2 Answers 2

29

You can use setTag. So, your code will look like,

final Button testButton = (Button) findViewById(R.id.button1);
testButton.setTag(1);
testButton.setText("Play");
testButton.setOnClickListener( new View.OnClickListener() {
    @Override
    public void onClick (View v) {
        final int status =(Integer) v.getTag();
        if(status == 1) {
            mPlayer.start();
            testButton.setText("Pause");
            v.setTag(0); //pause
        } else {
            testButton.setText("Play");
            v.setTag(1); //pause
        }
    }
});

About setTag

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks a lot gopai! I had a feeling it would require an if statement but not a setTag. thanks again!
3
private bool isPlaying=false;
final Button testButton = (Button) findViewById(R.id.button1);
testButton.setText("Play");
testButton.setOnClickListener( new View.OnClickListener() {

@Override
public void onClick (View v) {
if(!isPlaying){
  mPlayer.start();
  testButton.setText("Pause");
  isPlaying=true;
}else{
  mPlayer.stop();
  testButton.setText("Play");
  isPlaying=false;
}

I thing you've got the idea. Though, I'm not sure about MediaPlayer states.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.