如何让单选按钮在切换活动时不改变?

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

我有一个包含 2 个场景的 android 应用程序。主要活动和设置。当我从 mainactivity 转到 settingsactivity 并更改一个单选按钮并返回到 mainactivity 然后再返回时,该按钮返回到默认值。那是因为它总是转到 oncreate 方法。我如何才能 place/write Intent,使单选按钮不回到默认状态?

您是否尝试过使用一对 onSaveInstanceState 和 onRestoreInstanceState?您可以保存单选按钮的状态,以便稍后在应用重新加载您的页面时恢复它们。

这里有一些有用的 link 来自官方 Android 开发者网站的关于这两种方法的信息。 https://developer.android.com/reference/android/app/Activity.html#onSaveInstanceState(android.os.Bundle) https://developer.android.com/reference/android/app/Activity.html#onRestoreInstanceState(android.os.Bundle)

一旦单选按钮的状态发生变化,您应该保存它的持久性。对于设置,SharedPreferences 是最佳选择。 所以,

  1. 在组中创建可能的 RadioButton 集合(在 onCreate 方法中的 setContent 语句之后):
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. 一旦状态改变(因此,在 RadioGroupOnCheckedChangeListener 中),将其保存在 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. 在设置的onCreate中activity:读取之前保存的状态并相应地更新UI:
int option = getSharedPreferences("my_settings", Context.MODE_PRIVATE).getInt("sel_option", 0);

// set checked for the specific button
buttons.get(option).setChecked(true);