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?
setBackgroundResource when changing Activities
2.1k views Asked by Zach J. At
5
There are 5 answers
0
On
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.
0
On
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
You need to store the value on the image button in a static variable or SharedPreferences,
For example declare a variable
now on the img button click
and also do the following in onResume() of the activity: