Save togglebuttom state

0

Good afternoon!

As I could save the state of a togglebuttom, I created an app where I saved and erased an edittext, however I do not know how to save the state of that button, every time I left the app and back the button would be to be on delete mode, but it returns in save mode.

Could someone help me with how to do it?

    
asked by anonymous 10.02.2018 / 16:15

1 answer

1

Use SharedPreferences to save / get the status of ToggleButton (checked / unchecked)

When you start the activity, check the preferences in the preferences, and programmatically change the status of the button accordingly.

final SharedPreferences sp = PreferenceManager.getDefaultSharedPreferences(this); // Contexto

ToggleButton toggleButton = findViewById(R.id.toggleButton);
toggleButton.setChecked(sp.getBoolean("meuToggleButton", false));
...

To save the value in preferences, use the OnCheckedChangeListener , so always that the button is clicked its value will be saved (and later read when starting the activity)

toggleButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            SharedPreferences.Editor editor = sp.edit();
            editor.putBoolean("meuToggleButton", isChecked);
            editor.apply();
        }
    });
    
12.02.2018 / 13:00