Make Image Button Behave Like a Toggle Button

馋奶兔 提交于 2019-12-25 00:39:20

问题


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!


回答1:


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



回答2:


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.




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


来源:https://stackoverflow.com/questions/28655034/make-image-button-behave-like-a-toggle-button

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!