在Android中使用共享首选项更改背景颜色

时间:2013-06-28 09:58:08

标签: android sharedpreferences

我想用按钮更改应用的背景颜色。它应该在两种颜色之间切换,为此我使用了SharedPreference,但是>我还不知道如何存储用于切换的布尔值。 我明白了:

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 个答案:

答案 0 :(得分:0)

要从prefs保存并获取布尔值,您可以使用:

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

然后在你的Activity中使用它:

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