简体   繁体   中英

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!

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 .

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;
            } 
        }
    });

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();
            }
        }
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM