Make Image Button Behave Like A Toggle Button
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. Than
Solution 1:
you can use event's. like on click listener. get your imageView and setOnClickListener for this.
ImageViewmImageView= (ImageView) findViewById(R.id.sound_imageView);
Booleanflag=false;
mImageView.setOnClickListener(newView.OnClickListener() {
@OverridepublicvoidonClick(View view) {
if(flag) {
//play sound
flag = false;
} else {
//stop sound
flag = true;
}
}
});
Solution 2:
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.
Solution 3:
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(newView.OnClickListener() {
@OverridepublicvoidonClick(View v) {
if(musicPlayer!=null && musicPlayer.isPlaying()){
musicPlayer.stop();
}else{
musicPlayer=newMediaPlayer();
AssetFileDescriptorafd= getActivity().getAssets().openFd("AudioFile.mp3");
musicPlayer.setDataSource(afd.getFileDescriptor());
musicPlayer.prepare();
musicPlayer.start();
}
}
});
Post a Comment for "Make Image Button Behave Like A Toggle Button"