简体   繁体   English

无法从切换按钮到第二活动获得价值

[英]Cant get value from switch button to the second activity

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);
        }

you can create a class AppPreference like this:- 您可以像这样创建一个类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();
    }
}

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);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM