首页 > 解决方案 > Is it possible to save void in SharedPreferences

问题描述

I have a button which changes the color of the MainActivity but this works only if the app it is open if I exit the app and open again it return to normal color which is white. How to store with Shared Preferences do you have any idea how to do that because strings, int and boolean I can save but this function I don' have any idea.

This is my code.

MainActivity.class

public static final String Change_Color = "Change_Color";
private boolean switchOnOff;


  setContentView(R.layout.activity_main);

   if (switchOnOff == true) {
        setColorGreyImageButton();
        } else if(switchOnOff == false) {
            setColorWhiteImageButton();
        }


if(id == R.id.menu_back_white) {
   saveColor();
} else if (id == R.id.menu_back_black) {
   saveColor2();
}

 public void setColorGreyImageButton() {
        settings.setColorFilter(Color.parseColor("#757575"));
        voiceSearch.setColorFilter(Color.parseColor("#757575"));
        share.setColorFilter(Color.parseColor("#757575"));
        search.setColorFilter(Color.parseColor("#757575"));
        mainView.setBackgroundColor(Color.parseColor("#FFFFFF"));

SharedPreferences in MainActivity

public void saveColor() {
    SharedPreferences sharedPreferences = getSharedPreferences("Color", MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putBoolean(Change_Color, false);
    switchOnOff = sharedPreferences.getBoolean(Change_Color, false);

}

public void saveColor2() {
    SharedPreferences sharedPreferences = getSharedPreferences("Color", MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putBoolean(Change_Color, true);
    switchOnOff = sharedPreferences.getBoolean(Change_Color, true);
}

标签: androidsharedpreferences

解决方案


Use these methods in your activity class:

private boolean getChangeColor() {
    SharedPreferences sharedPreferences = getSharedPreferences("Color", MODE_PRIVATE);
    return sharedPreferences.getBoolean(getPackageName() + ".change_color", false);
}

private void saveChangeColor(boolean changeColor) {
    SharedPreferences sharedPreferences = getSharedPreferences("Color", MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPreferences.edit();
    editor.putBoolean(getPackageName() + ".change_color", changeColor);
    editor.apply();
}

In onCreate() check the boolean value stored in SharedPreferences:

   switchOnOff = getChangeColor();
   if (switchOnOff) {
       setColorGreyImageButton();
   } else {
       setColorWhiteImageButton();
   }

and when you want to change the value in SharedPreferences call:

saveChangeColor(true); 

or

saveChangeColor(false);

推荐阅读