Save togglebuttom state

Asked

Viewed 40 times

0

Good afternoon!

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

Could someone give me a hand on how to do?

  • What code you use to save Edittext?

  • I used Sharedpreferences. I implemented the example below and it worked perfectly.

1 answer

1

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

When starting Activity, check the saved value in the preferences, and programmatically change the status of the agreed button.

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

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

To save the value in the preferences, use the Oncheckedchangelistener, thus, whenever the button is clicked its value will be saved (and later read upon starting 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();
        }
    });
  • Thank you, I used the example above and it worked.

  • Welcome. I’m glad I helped. If the answer solved the problem, please, accept it.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.