Rodriquez Rodriquez - 2 months ago 11
Android Question

Double action on button click, how to do it good

i Create this for double action on click

private int pos = 0;

private void changeImageVolumeOffOn() {
buttonMuteVolume.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (pos == 0) {
pos++;
buttonMuteVolume.setBackgroundResource(R.drawable.volume_off);
} else {
pos--;
buttonMuteVolume.setBackgroundResource(R.drawable.volume_on);
}
}
});
}


But i think this is not good way for do this. I need emergency change the image only for showing it to my friends. How to do double action for click?

Answer

To remove the if statement you could use a ternary operator

boolean clicked = false;

private void changeImageVolumeOffOn() {
    buttonMuteVolume.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            clicked = !clicked;
            buttonMuteVolume.setBackgroundResource(clicked ? R.drawable.volume_off : R.drawable.volume_on);
        }
    });
}
Comments