Reputation:
I made a switch button for something like "dark mode",basically it should change the app color, and it does, but only in the first activity, then, when i try to pass the boolean value to the 2nd activity it doesn't change the color of anything.
Main activity :
public void nightview(View view) {
Intent intent4 = new Intent(this, DisplayResultActivit.class);
Switch sw1 = findViewById(R.id.nightview);
boolean switchstate = sw1.isChecked();
intent4.putExtra("state", switchstate);
if (switchstate) {
//nightview
View lay = findViewById(R.id.layout);
...
2nd activity :
boolean state = getIntent().getExtras().getBoolean("state");
if (state) {
//nightview
View lay2 = findViewById(R.id.layout2);
lay2.setBackgroundColor(Color.BLACK);
TextView tv1 = findViewById(R.id.textView);
tv1.setTextColor(Color.WHITE);
tv.setTextColor(Color.WHITE);
} else {
//dayview
View lay2 = findViewById(R.id.layout2);
lay2.setBackgroundColor(Color.WHITE);
TextView tv1 = findViewById(R.id.textView);
tv1.setTextColor(Color.BLACK);
tv.setTextColor(Color.BLACK);
}
Upvotes: 0
Views: 39
Reputation: 1976
you can create a class AppPreference like this:-
public class AppPrefrences {
private static SharedPreferences mPrefs;
private static SharedPreferences.Editor mPrefsEditor;
public static boolean getSwitchValue(Context ctx) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
return mPrefs.getBoolean("switch", false);
}
public static void setSwitchValue(Context ctx, Boolean value) {
mPrefs = PreferenceManager.getDefaultSharedPreferences(ctx);
mPrefsEditor = mPrefs.edit();
mPrefsEditor.putBoolean("switch", value);
mPrefsEditor.commit();
}
}
and set values from all the activities like this:- to set switch value in preference:-
setSwitchValue(MainActivity.this, true);
to get switch value in all activites:-
getSwitchValue(MainActvity2.class);
Upvotes: 1