0

How to maintain the state of toggle buttons, like if we press button1 then it remembers the on state of button1 and won't allow us to press button2, and vice versa. Please help me out in solving this problem.

Brian Tompsett - 汤莱恩
  • 5,195
  • 62
  • 50
  • 120
Sam
  • 21
  • 2
  • 6

1 Answers1

0

Try this.

Declare variables

ToggleButton mToggleOne;
ToggleButton mToggleTwo;

In onCreate

mToggleOne = (ToggleButton) findViewById(R.id.toggle_button1);
mToggleTwo = (ToggleButton) findViewById(R.id.toggle_button2);

SharedPreferences spref = getSharedPreferences();
if(spref.getBoolean("one", false)) {
    mToggleOne.setChecked(true);
    mToggleTwo.setEnabled(false);    
} else if(spref.getBoolean("two", false)) {
    mToggleTwo.setChecked(true);
    mToggleOne.setEnabled(false);    
}
mToggleOne.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
       mToggleTwo.setEnabled(!isChecked);
       getSharedPreferences().edit()
           .putBoolean("one", isChecked)
           .apply();
       //other code
    }
});

mToggleTwo.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
       mToggleOne.setEnabled(!isChecked);
       getSharedPreferences().edit()
           .putBoolean("two", isChecked)
           .apply();
       //other code
    }
});
Anton Shkurenko
  • 4,051
  • 5
  • 26
  • 59
  • ohh yeah I did that :) – Sam Jul 09 '15 at 19:16
  • but a simple problem occurred, actually side by side i was saving the state of toggle button, but after applying this code its not saving the state of toggle button anymore. – Sam Jul 09 '15 at 19:17
  • @Sam where do you wanna save it? You can try onSaveInstanceState like here: http://developer.android.com/training/basics/activity-lifecycle/recreating.html Or try to put into preferences, like here: http://stackoverflow.com/questions/23024831/android-shared-preferences-example – Anton Shkurenko Jul 09 '15 at 19:23
  • actually i want button1 should remain "on" until and unless i want to off the button, so for that i have to save the state of toggle button that it it should remember it is on. Same for the button2 – Sam Jul 09 '15 at 19:26
  • @Sam you can call mToggleOne.isChecked() to retrieve info about state – Anton Shkurenko Jul 09 '15 at 19:30
  • but its not working after pressing the backkey to the app, when i opened it, both button setChecked.(off) – Sam Jul 09 '15 at 19:39
  • To make everything clear: You wanna retrieving states of the toggled buttons after closing and opening app? Or after going to another activity and coming back? – Anton Shkurenko Jul 09 '15 at 19:40
  • i want to retrieve the states of the toggled buttons after closing and opening app. – Sam Jul 09 '15 at 19:42
  • Yes! thank you so very much :) it is working perfectly :) Stay Blessed – Sam Jul 09 '15 at 20:03