Changing background colour with SharedPreference in Android

旧巷老猫 提交于 2020-01-06 08:14:10

问题


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);
    }
}

回答1:


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);
    }
}


来源:https://stackoverflow.com/questions/17362013/changing-background-colour-with-sharedpreference-in-android

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!