简体   繁体   中英

save the state of my togglebutton after return in the same activity or restart application

everybody! I try to save the state of my ToggleButton. In fact, i would like to have the same state after user restart his application or return in this activity.

But for example when i return in my previous activity and then when i re-return in my activity where is my ToggleButton, i see that the ToggleButton status is not registered. If anyone can help me?

Like you can see, i use setDefaults to save the state of my ToggleButton and getDefaults to recover it.

public class OnOff extends Activity {

    ToggleButton toggle1;
    ToggleButton toggle2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.on_off);
        // Show the Up button in the action bar.
        setupActionBar();

        toggle1 = (ToggleButton) findViewById(R.id.ontoggle1);
        toggle1.setChecked(getDefaults("etatToggle",this));
        setDefaults("etatToggle", toggle1.isChecked(), this);
    }


    //Fonction appelée pour enregistrer en mémoire, ici en l'occurence l'état du ToggleButton: true ou false
    public static void setDefaults(String key, Boolean value, Context context)
    {
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = prefs.edit();
        editor.putBoolean(key, value);
        editor.commit();
    }

    //Fonction appelée pour récupérer ce qui a été saisi en mémoire
    public static Boolean getDefaults(String key, Context context)
    {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getBoolean(key, true);
    }
}
@Override
public void onStart(){
    super.onStart();

    toggle1.setChecked(getDefaults("etatToggle",this));
}


@Override
public void onStop(){
    super.onStop();

    setDefaults("etatToggle", toggle1.isChecked(), this);
}

Since you are calling the following

    setDefaults("etatToggle", toggle1.isChecked(), this);

in onCreate() , everytime you start your application the ToggleButton is checked irrespective of the previous state of the ToggleButton when the application was closed. So this line of code should be placed as follows-

    toggle1.setOnClickListener(new View.OnClickListener() {

    public void onClick(View v) {

           setDefaults("etatToggle", toggle1.isChecked(), OnOff.this);
    }
});

so that the state of the ToggleButton is saved when you click it and thereby the ToggleButton will retain its previous state when the application is started again.

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