0

I want to change the background color of my app with a button. It should switch between two colors, for this I used SharedPreference, but >I don't know yet how to store the boolean for switching.. I got this:

public void method1(View view) {

    SharedPreferences settings = getSharedPreferences(PREFS, 0);
    SharedPreferences.Editor editor = settings.edit();
    editor.putBoolean("modus", !modus);
    editor.commit();
    if (settings.getBoolean("modus", false)) {
        int i = Color.GREEN;
        LinearLayout layout = (LinearLayout) findViewById(R.id.mylayout);
        layout.setBackgroundColor(i);
    } else {
        int j = Color.BLUE;
        LinearLayout layout = (LinearLayout) findViewById(R.id.mylayout);
        layout.setBackgroundColor(j);
    }
}
hello_there
  • 1
  • 1
  • 4

1 Answers1

0

To save and get boolean from prefs you can use this :

public class Settings
{

private static final String PREFS_NAME = "com.yourpackage.Settings";
private static final String MODUS = "Settings.modus";

private static final SharedPreferences prefs = App.getContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);

private Settings()
{

}

public static void setUseGreen(boolean useGreen)
{
    Editor edit = prefs.edit();

    edit.putBoolean(MODUS, useGreen);


    edit.commit();
}

public static boolean useGreen()
{
    return prefs.getBoolean(MODUS, false);
}
}

And then in your Activity just use this :

    @Override
protected void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);
    this.setContentView(R.layout.your_layout);

    initModus();
}

public void initModus()
{
    CheckBox modus = (CheckBox)findViewById(R.id.yourChackBoxId);
    modus.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean checked)
        {
            Settings.setUseGreen(checked);
            changeColor(checked);
        }
    });

    boolean useGreen = Settings.useGreen();
    modus.setChecked(useGreen);
}


private void changeColor(boolean checked)
{
    LinearLayout layout = (LinearLayout) findViewById(R.id.mylayout);

    if (useGreen) {
        int green = Color.GREEN;
        layout.setBackgroundColor(green);
    } else {
        int blue = Color.BLUE;
        layout.setBackgroundColor(blue);
    }
}
Yakiv Mospan
  • 8,174
  • 3
  • 31
  • 35
  • Thanks, but I just had to change one line: editor.putBoolean("modus", !settings.getBoolean("modus", false)); And my code works just fine :) – hello_there Jun 28 '13 at 13:07