Play and Pause using the same button
Clash Royale CLAN TAG#URR8PPP
Play and Pause using the same button
I want to make it only one button that has two function. First click I want to play it and second click I want to pause it. And when I click it again It continues where it left off.
JAVA SIDE;
MediaPlayer ocean;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sound);
ocean=MediaPlayer.create(Sound.this,R.raw.ocean);
public void play(View v)
ocean.start();
public void pause(View V)
ocean.pause();
}
ACTIVITY SIDE:
<Button
android:id="@+id/play"
android:layout_width="165dp"
android:layout_height="0dp"
android:layout_marginBottom="285dp"
android:background="@drawable/oceansound"
android:onClick="play"
android:text=""/>
3 Answers
3
Use a flag that indicates if the player is on or off:
Boolean isOn = false;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sound);
ocean=MediaPlayer.create(Sound.this,R.raw.ocean);
public void play(View v)
if (!isOn)
ocean.start();
isOn = true;
else
ocean.pause();
isOn = false;
}
I'm glad, and also check it as the right answer
– user8959091
Aug 12 at 9:32
Since you have ocean is MediaPlayer object, you can check if the song is playing by ocean.isPlaying(), hope it will help you.
public class MainActivity extends AppCompatActivity
MediaPlayer ocean;
@Override
protected void onCreate(Bundle savedInstanceState)
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sound);
ocean = MediaPlayer.create(this, R.raw.ocean);
public void play(View view)
if (ocean.isPlaying())
ocean.pause();
else
ocean.start();
It's simple, use a checker variable to track the action.
Create a global variable isPlay
in int / boolean, in your play
, make a if statement to check whether it is playing or in pause, if playing, ocean.pause();
, set the button background to pause and vice versa.
isPlay
play
ocean.pause();
Hope it helps
By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.
Ayyy it works! thank you!!
– Syed Shahrul Shafiq
Aug 12 at 9:30