0

我想用一个按钮更改我的应用程序的背景颜色。它应该在两种颜色之间切换,为此我使用了 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);
    }
}
4

1 回答 1

0

要从首选项保存和获取布尔值,您可以使用以下命令:

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

然后在你的活动中使用这个:

    @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);
    }
}
于 2013-06-28T10:04:07.397 回答