[英]Cant get value from switch button to the second 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);
...
第二活动:
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);
}
您可以像这样创建一个类AppPreference:-
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();
}
}
并从以下所有活动中设置值:-优先设置开关值:-
setSwitchValue(MainActivity.this, true);
在所有活动中获取切换值:-
getSwitchValue(MainActvity2.class);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.