简体   繁体   中英

How to save state of my activity after it is destroyed

I use following code to change background of my buttons:

 case R.id.purple:
          for (Button currentButton : buttons) {
                currentButton.setBackgroundResource(R.drawable.purple);
            }

It changes color of all buttons, but whenever i change screen orientation or take activity to bacground or close my app, the backround color reverts to its default value.How can i save this information so that it is not lost and color of buttons remain same as i assigned it. To save integral or string values i am using this code:

@Override
public void onSaveInstanceState(Bundle savedInstanceState) {
  super.onSaveInstanceState(savedInstanceState);
  savedInstanceState.putString("MyString", inputText.getText().toString());
  // etc.
}

But i don't know how to save state of buttons.

You can save the name of the drawable your are using as a string

savedInstanceState.putString("ButtonColor", "purple");

Then in onCreate

if(savedInstance != null)
{
String drawableName = savedInstance.getString("ButtonColor");
int drawableResourceId = getResources().getIdentifier(drawableName, "drawable", getPackageName());
                    currentButton.setBackgroundResource(getResources().getDrawable(drawableResourceId ));
}

onSaveInstanceState() won't trigger if your activity get destroyed by pressing BACK button for example and in some other cases.

The best way to save current state is to save it in SharedPreferences in onDestroy() or onPause() and to load in onCreate(). Here's an example:

@Override
public void onDestroy() {
  super.onDestroy();
  SharedPreferences user = getUserDataSharedPreferences(this);
  SharedPreferences.Editor ed = user.edit();
  ed.putInt("myColor", R.drawable.purple);
  ed.commit();
}

@Override
public void onCreate(Bundle savedInstanceState) {
  super.onCreate(savedInstanceState);
  SharedPreferences user = getUserDataSharedPreferences(this);
  user.getInt("myColor", 0);
}

If you call SharedPreferences outside of activity - replace this with context or getActivity() .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM