Java 无法从切换按钮获取到第二个活动的值
我为类似“暗模式”的东西做了一个切换按钮,基本上它应该改变应用程序的颜色,它确实会改变,但只有在第一个活动中,然后,当我尝试将布尔值传递给第二个活动时,它不会改变任何东西的颜色 主要活动:Java 无法从切换按钮获取到第二个活动的值,java,android,android-intent,android-activity,Java,Android,Android Intent,Android Activity,我为类似“暗模式”的东西做了一个切换按钮,基本上它应该改变应用程序的颜色,它确实会改变,但只有在第一个活动中,然后,当我尝试将布尔值传递给第二个活动时,它不会改变任何东西的颜色 主要活动: public void nightview(View view) { Intent intent4 = new Intent(this, DisplayResultActivit.class); Switch sw1 = findViewById(R.id.nightview)
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);
}
第二项活动:
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);
我们能看到startactivity的意图吗?@CarlosLópezMarí这是计算器,所以它取决于我将单击什么,在切换按钮方法中,我没有startactivity的意图。更改了,但它仍然只显示白天模式,即使我将其更改为夜间模式,就像它没有从第一个活动中获取值一样。现在它工作了,但问题是我不想让这个方法启动触觉,我不想让它进入第二个活动,我能做什么?你想做什么?根据您的问题,我已经向您推荐了我所知道的。当我编写StartActivity时,它将转到第二个活动,我希望它保持在第一个活动上,但只将值传递给第二个活动。您可以将开关值保存在共享首选项中,以便在应用程序中的任何位置使用。