Changing Background Colour With Sharedpreference In Android
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 bool
Solution 1:
To save and get boolean from prefs you can use this :
publicclassSettings
{
privatestaticfinalStringPREFS_NAME="com.yourpackage.Settings";
privatestaticfinalStringMODUS="Settings.modus";
privatestaticfinalSharedPreferencesprefs= App.getContext().getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE);
privateSettings()
{
}
publicstaticvoidsetUseGreen(boolean useGreen)
{
Editoredit= prefs.edit();
edit.putBoolean(MODUS, useGreen);
edit.commit();
}
publicstaticbooleanuseGreen()
{
return prefs.getBoolean(MODUS, false);
}
}
And then in your Activity just use this :
@OverrideprotectedvoidonCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.setContentView(R.layout.your_layout);
initModus();
}
publicvoidinitModus()
{
CheckBoxmodus= (CheckBox)findViewById(R.id.yourChackBoxId);
modus.setOnCheckedChangeListener(newCompoundButton.OnCheckedChangeListener() {
@OverridepublicvoidonCheckedChanged(CompoundButton compoundButton, boolean checked)
{
Settings.setUseGreen(checked);
changeColor(checked);
}
});
booleanuseGreen= Settings.useGreen();
modus.setChecked(useGreen);
}
privatevoidchangeColor(boolean checked)
{
LinearLayoutlayout= (LinearLayout) findViewById(R.id.mylayout);
if (useGreen) {
intgreen= Color.GREEN;
layout.setBackgroundColor(green);
} else {
intblue= Color.BLUE;
layout.setBackgroundColor(blue);
}
}
Post a Comment for "Changing Background Colour With Sharedpreference In Android"