如何在第一个 activity 中检查单选按钮,同时从 Android 应用程序中的第二个 activity 返回

How to check Radio Button in first activity while coming back from second activity in Android application

功能:我的应用程序中有三个活动,在 activity 一个活动中我有 2 组单选按钮。当用户在第一组单选按钮上单击“是”时,他将移动到 activity 第二个。当他回到原来的 activity 时,应该选中单选按钮。 之后,如果他点击第二个是,他应该被带到 activity 3rd。同样,当他返回主 activity 时,两个单选按钮都应选中是。

问题:我几乎可以执行所有功能,除了当他从第 3 次回来时 activity 只选择了一个单选按钮。

在活动的 onSaveInstanceState 回调中使用 your_radio_group_id.getCheckedRadioButtonId() 保存选中的项目索引,然后在 onCreate 或 onRestoreInstanceState 方法中恢复状态。 您可以在此处找到更多详细信息:https://developer.android.com/reference/android/app/Activity.html#onSaveInstanceState(android.os.Bundle)

假设您的 SecondActivity 已经启动。

Intent i=new Intent(context,yourSecondActivity.class);
i.startActivity();
//Now second Activity will be opened.

在您的第二个 activity 中覆盖 onBackPressed 方法并添加以下内容:

super.onBackPressed();
Intent i=new Intent(context,yourFirst.class);
i.putExtra("who", "yourSecondActivity");
i.startActivity

最后,您必须将以下内容添加到您的第一个 activity onCreate 方法中:

Intent intent = getIntent();
if ( intent.getStringExtra("who") == "yourSecondActivity" ){
   //Change the Radio Button so that it is checked.
   RadioButton b = (RadioButton) findViewById(R.id.yourRadioButtonId);
   b.setChecked(true);
}

因此,当您希望 activity 的复选框被选中时,您可以在意图中添加额外信息。这只是一个小例子。

您可以使用的另一种方法是将单选按钮的状态保存在 SharedPreferences 中。当您回到主 activity 时,您可以使用相同的密钥从相同的位置恢复它。 这种方法允许您设置单选按钮,即使用户关闭 activity.

正在保存密钥:

  SharedPreferences sharedPref = MainActivity.this.getSharedPreferences(Context.MODE_PRIVATE);
    SharedPreferences.Editor editor = sharedPref.edit();
    editor.putBoolean("state_of_1st_radio_button",true); 
// true or false depending on what you want to save.
    editor.commit();

获取密钥:

SharedPreferences sharedPref = MainActivity.this.getSharedPreferences(Context.MODE_PRIVATE);
if(sharedPref.getBoolean("state_of_1st_radio_button",false) == true){
     //set the radio button true
}

请注意,sharedPref.getBoolean 方法中的第二个参数是默认值,这意味着如果没有要从 SharedPrefs 检索的对象,它将 return 该默认值。

希望对您有所帮助。