There is a button handler:

change.setOnClickListener(new OnClickListener(){ public void onClick(View arg0) { bglayout.setBackgroundColor(333333); } }); 

How to do it so that when you restart the application, this color is preserved?

Potentially, not only color. Thank you in advance.

  • If you are given an exhaustive answer, mark it as correct (a daw opposite the selected answer). - Nicolas Chabanovsky

2 answers 2

To save any (small) parameters between application restarts, you can use the SharedPreferences class.

A simple example:

Add a field to the Activity class:

 private SharedPreferences mSettings; 

Next, in the onCreate() method, load and apply the saved color (if it was saved):

 mSettings = getSharedPreferences("my_settings", Context.MODE_PRIVATE); if (mSettings.contains("my_background_color")) { int color = mSettings.getInt("my_background_color", 0); bglayout.setBackgroundColor(color); } 

And in the onStop() method, save the color:

 SharedPreferences.Editor editor = mSettings.edit(); Drawable background = bglayout.getBackground(); if (background instanceof ColorDrawable) editor.putInt("my_background_color", ((ColorDrawable) background).getColor()); editor.apply(); 
  • Tell me, does this method work, what would it be in the settings? that is, we pass the variable through the intent, and then we simply use it. or do it in a different way? - JaredBay
  • @JaredBay, I didn’t quite understand the question, but if you asked whether it is possible to save the application settings in this way, yes, you can. - post_zeew 2:01
  • You understood me correctly: D thanks for the explanation. - JaredBay 3:12

In Android, there are special methods in the Activity to save / restore state : onSaveInstanceState and onRestoreInstanceState .

In onSaveInstanceState you can save the button color:

 @Override public void onSaveInstanceState(Bundle savedInstanceState) { // сохраняем цвет кнопки savedInstanceState.putInt("btn_bg", ((ColorDrawable) change.getBackground()).getColor()); super.onSaveInstanceState(savedInstanceState); } 

And in onRestoreInstanceState restore:

 public void onRestoreInstanceState(Bundle savedInstanceState) { super.onRestoreInstanceState(savedInstanceState); // устанавливаем цвет, который сохранили перед закрытием пиложения change.setBackgroundColor(savedInstanceState.getInt("btn_bg")); } 
  • "when restarting the application" it will not work. - Yura Ivanov