Search code examples
javaandroidandroid-activityradio-button

How to make the radio buttons not to change when switching the activities?


i've got an android app with 2 scenes. mainactivity and settings. When I go from the mainactivity to the settingsactivity and change a radiobutton and go back to the mainactivity and than again back, the button goes back to default. Thats because it always goes to the oncreate method. how do I have to place/write the Intent, that the radiobuttons don't go back to default?


Solution

  • You should save state of radio buttons once it changed in some persistance. For the settings, SharedPreferences is the optimal choice. So,

    1. Create collection of possible RadioButtons in the group (after setContent statement in onCreate method):
    RadioGroup rGroup = findViewById(R.id.radioGroup1);
    
    List<RadioButton> buttons = new ArrayList();
    buttons.add(rGroup.findViewById(R.id.radioButton1);
    buttons.add(rGroup.findViewById(R.id.radioButton2);
    // ...
    }
    
    1. Once state is changed (so, in OnCheckedChangeListener of the RadioGroup) , save it in the SharedPreferences:
    // find RadioButton
    RadioGroup rGroup = findViewById(R.id.radioGroup1);
    RadioButton checkedRadioButton = rGroup.findViewById(rGroup.getCheckedRadioButtonId());
    
    // define selected option value
    int selectedOption = 0;
    for (int i = 0; i < buttons.size(); i++) {
      if (checkedRadioButton.getId() == buttons.get(i).getId()) {
        selectedOption = i;
        break;
      }
    }
    
    // write state to SP
    getSharedPreferences("my_settings", Context.MODE_PRIVATE).edit().putInt("sel_option", selectedOption).apply()
    
    1. In the onCreate of settings activity: read previously saved state and update UI accordingly:
    int option = getSharedPreferences("my_settings", Context.MODE_PRIVATE).getInt("sel_option", 0);
    
    // set checked for the specific button
    buttons.get(option).setChecked(true);