throwaway123
throwaway123

Reputation: 39

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. Thank you!

Upvotes: 0

Views: 1403

Answers (3)

ARGHA
ARGHA

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

Ashkan
Ashkan

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

happydude
happydude

Reputation: 3889

There are a few Views 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

Related Questions