You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

为何从第二个Activity返回时第一个Activity的RadioButton被取消选中?

问题解答:返回第一个Activity后RadioButton选中状态丢失

这是Android开发里很常见的生命周期相关问题,我来帮你捋清楚原因和解决办法:

为什么会出现这个情况?

当你从MainActivity跳转到第二个Activity(jenis)时,MainActivity会进入**暂停(onPause)**状态。如果此时系统需要释放内存,MainActivity可能会被完全销毁。当你点击返回按钮回到MainActivity时,系统会重新创建这个Activity的实例——这时候原来的RadioButton选中状态并没有被保存下来,所以就出现了选中状态丢失的情况。

解决办法:保存并恢复RadioButton的选中状态

你需要在MainActivity中重写两个生命周期方法,来保存和恢复选中状态:

1. 保存选中状态到Bundle

在MainActivity中添加onSaveInstanceState方法,把当前选中的RadioButton的ID存起来:

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    
    // 找出当前被选中的RadioButton的ID
    int selectedRadioId = -1;
    if (keroh.isChecked()) selectedRadioId = keroh.getId();
    else if (molek.isChecked()) selectedRadioId = molek.getId();
    else if (tangga.isChecked()) selectedRadioId = tangga.getId();
    else if (bandar.isChecked()) selectedRadioId = bandar.getId();
    else if (bukit.isChecked()) selectedRadioId = bukit.getId();
    else if (batu.isChecked()) selectedRadioId = batu.getId();
    else if (tanjung.isChecked()) selectedRadioId = tanjung.getId();
    else if (klebang.isChecked()) selectedRadioId = klebang.getId();
    
    // 把ID存入Bundle
    outState.putInt("selected_radio_id", selectedRadioId);
}

2. 在Activity重建时恢复选中状态

在MainActivity的onCreate方法中,取出之前保存的ID,重新设置RadioButton的选中状态:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_main_activity_layout);
    
    // 这里要先初始化你的所有RadioButton实例,比如:
    // keroh = findViewById(R.id.keroh);
    // molek = findViewById(R.id.molek);
    // ...其他RadioButton
    
    // 如果之前保存过状态,就恢复
    if (savedInstanceState != null) {
        int savedRadioId = savedInstanceState.getInt("selected_radio_id", -1);
        if (savedRadioId != -1) {
            RadioButton targetRadio = findViewById(savedRadioId);
            if (targetRadio != null) {
                targetRadio.setChecked(true);
            }
        }
    }
}

你也可以选择在onRestoreInstanceState方法中做恢复操作,效果是一样的,看你个人习惯。

补充说明

如果你的MainActivity只是暂时被后台挂起、没有被系统销毁,那返回时选中状态会自动保留;但我们必须考虑到系统销毁Activity的情况,所以上面的保存恢复逻辑是必要的。

内容的提问来源于stack exchange,提问作者Fatihah Hanafiah

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.29 08:57:25