简体   繁体   中英

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:-

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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