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?
You should save state of radio buttons once it changed in some persistance. For the settings, SharedPreferences
is the optimal choice.
So,
RadioButton
s 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);
// ...
}
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()
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);