Question

In one of my activities I have an ImageButton that on click changes the background resource by using setBackgroundResource(). I works fine in that activity but when I leave that activity and come back to it the button has changed back to its default background that was set in the XML. Is there a way to permanently set the background resource to something until the button is clicked again?

Was it helpful?

Solution

You need to store the value on the image button in a static variable or SharedPreferences,

For example declare a variable

public static int bgresource;

now on the img button click

if(something) {
bgresource = R.drawable.img1
} else {
bgresource = R.drawable.img2
}

mylayout.setBackgroundResource(bgresource);

and also do the following in onResume() of the activity:

mylayout.setBackgroundResource(bgresource);

OTHER TIPS

Use SharedPreferences.

When changing the Background:

getSharedPreferences("background", MODE_PRIVATE).edit().putString("background","background_nr_1").commit();

or

getSharedPreferences("background", MODE_PRIVATE).edit().putString("background","background_nr_2").commit();

and so on. This will save the string, describing your current background to sharedPreferences.

In the onCreate-Method you need to put:

String back = getSharedPreferences("background", MODE_PRIVATE).getString("background");

This will get you "background_nr_x" in back. Now you can choose the background:

if (back.equals("background_nr_1") { // set the Background associated with nr_1
else if (.... "nr_2") ...

Note: this will restore the current chosen background, even if the App was closed.

Save the URL/id of the image you use as background in SharedPreferences and make sure to set it everytime the activity is created. Otherwise the background specified in your XML file will be used when the activity is created the next time.

You should overwrite your Activity onResume() method. Make your activity or button keep the state (pressed or not pressed) and, at the onResume() method, check this state and change the background.

You can use a trick like this:

    //outside the onCreate:
    boolean resourceIsSet = false;

    //inside the onCreate:
    if(!resourceIsset) {
        setBackgroundResource();
        resourceIsset= true;
    }

Or you can use a SharedPreferences as other suggested

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top