要从首选项保存和获取布尔值,您可以使用以下命令:
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);
}
}