Reputation: 39
How can I have an on and off state for an Image Button? My goal is to have sound play when the image button is clicked, and for sound to stop when the button is clicked again. Thank you!
Upvotes: 0
Views: 1403
Reputation: 31
You can do it manually. First when you will click the button you will check whether the music is running or not. If it is running then stop it , if not running then play it. Something like that -
imageButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if(musicPlayer!=null && musicPlayer.isPlaying()){
musicPlayer.stop();
}else{
musicPlayer=new MediaPlayer();
AssetFileDescriptor afd = getActivity().getAssets().openFd("AudioFile.mp3");
musicPlayer.setDataSource(afd.getFileDescriptor());
musicPlayer.prepare();
musicPlayer.start();
}
}
});
Upvotes: 0
Reputation: 1378
you can use event's. like on click listener. get your imageView and setOnClickListener for this.
ImageView mImageView = (ImageView) findViewById(R.id.sound_imageView);
Boolean flag = false;
mImageView.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if(flag) {
//play sound
flag = false;
} else {
//stop sound
flag = true;
}
}
});
Upvotes: 1
Reputation: 3889
There are a few View
s that exist in Android that provide toggle functionality like you are looking for. You might want to research the android.widget.CompoundButton
class for ideas, or reference this tutorial.
Upvotes: 1