How to clear a background image when switching images in android

70 Views Asked by At

I have a button which switches between 2 images depending on the number of clicks...sometimes I get after leaving the activity and returning, both images show. How do make sure that only 1 image is showing?

Here is the code for the swap:

public void swapImageButton() {
    swapCount ++;
    if(swapCount % 2 == 0) {
        mStomachImageButton.setBackground(getDrawable(image1));
        mFartImageButton.setBackground(getDrawable(image2));
    } else {
        mStomachImageButton.setBackground(getDrawable(image2));
        mFartImageButton.setBackground(getDrawable(image1));
    }
}
2

There are 2 best solutions below

0
On

Use a static variable for count.

static int count=0;

public void swapImageButton() {

    if(count == 0) {
       //show you image when clicked first time
        count=1;
    } else {
        //show you image when clicked second time
        count=0;
    }
}
0
On

The two best ways to save the state of the control are:

I would go with the bundle, but that requires understanding the lifecycle of an activity. Btw, avoid the static variable idea.