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

Android Kotlin:RadioGroup选中ID无法通过SharedPreferences保存恢复

修复RadioGroup选中状态持久化问题

你的代码存在几个关键问题导致计量单位的选中状态无法正确保存和恢复,以下是修复方案:

问题分析

  1. 错误修改RadioButton的ID:在OnCheckedChangeListener中,你将选中的RadioButton的ID设置为radio_group.checkedRadioButtonId,这是完全不必要的操作——checkedRadioButtonId本身就是选中按钮的ID,修改它会导致后续的ID匹配失效。
  2. 使用Float类型保存整数ID:RadioButton的ID是整数,用putFloat和getFloat保存会引入精度问题,应该直接使用整数类型。
  3. 未同步选中状态到RadioGroup:加载保存的单位ID后,没有调用radio_group.check(unit)来恢复选中状态。
  4. onResume方法错误重置unit变量:onResume中unit = radio_group.checkedRadioButtonId会覆盖已保存的ID值,导致恢复逻辑失效。

修复后的代码

修改后的Kotlin代码

package com.example.stepstomountdoom

import android.content.Context
import android.content.Intent
import android.os.Bundle
import android.util.Log
import android.widget.*
import androidx.appcompat.app.AppCompatActivity

class AsetuksetActivity : AppCompatActivity() {

    private var cm = 0
    private var unit = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_asetukset)

        // 先初始化所有视图
        val buttonSettings = findViewById<ImageView>(R.id.koti_button)
        val testTextUnit = findViewById<TextView>(R.id.test_textUnit)
        val radioGroup = findViewById<RadioGroup>(R.id.radio_group)
        val radioButtonKm = findViewById<RadioButton>(R.id.radioBtn_km)
        val radioButtonMi = findViewById<RadioButton>(R.id.radioBtn_mi)
        val testTextHeight = findViewById<TextView>(R.id.test_textHeight)
        val userHeight = findViewById<NumberPicker>(R.id.user_height)

        // 加载保存的数据
        loadHeightData()
        loadUnitData()

        // 恢复身高选择
        userHeight.value = cm
        // 恢复单位选中状态
        if (unit != 0) {
            radioGroup.check(unit)
        }

        // 返回主页按钮逻辑
        buttonSettings.setOnClickListener {
            val intent = Intent(this, MainActivity::class.java)
            startActivity(intent)
        }

        // 单选按钮切换逻辑
        radioGroup.setOnCheckedChangeListener { _, checkedId ->
            testTextUnit.text = "$checkedId"
            unit = checkedId
            saveUnitData()
        }

        // 身高选择器配置
        userHeight.minValue = 0
        userHeight.maxValue = 250
        userHeight.wrapSelectorWheel = false

        userHeight.setOnValueChangedListener { _, _, newValue ->
            testTextHeight.text = "Selected number $newValue"
            cm = newValue
            saveHeightData()
        }
    }

    override fun onResume() {
        super.onResume()
        val userHeight = findViewById<NumberPicker>(R.id.user_height)
        val radioGroup = findViewById<RadioGroup>(R.id.radio_group)
        
        // 恢复身高
        userHeight.value = cm
        // 恢复单位选中状态
        if (unit != 0) {
            radioGroup.check(unit)
        }
    }

    private fun saveHeightData() {
        val sharedPreferences = getSharedPreferences("myPrefs", Context.MODE_PRIVATE)
        val editor = sharedPreferences.edit()
        editor.putFloat("key", cm.toFloat())
        editor.apply()
    }

    private fun loadHeightData() {
        val sharedPreferences = getSharedPreferences("myPrefs", Context.MODE_PRIVATE)
        val savedNumber = sharedPreferences.getFloat("key", 0f)
        Log.d("AsetuksetActivity", "$savedNumber")
        cm = savedNumber.toInt()
    }

    private fun saveUnitData() {
        val sharedPreferences = getSharedPreferences("myPrefs", Context.MODE_PRIVATE)
        val editor = sharedPreferences.edit()
        // 使用Int类型保存ID
        editor.putInt("key2", unit)
        editor.apply()
    }

    private fun loadUnitData() {
        val sharedPreferences = getSharedPreferences("myPrefs", Context.MODE_PRIVATE)
        // 使用Int类型加载ID,默认值设为radioBtn_km的ID(或你想要的默认选项)
        val savedId = sharedPreferences.getInt("key2", R.id.radioBtn_km)
        Log.d("AsetuksetActivity", "$savedId")
        unit = savedId
    }
}

关键修复点说明

  1. 移除错误的ID赋值:删除radioButton_km.id = radio_group.checkedRadioButtonId和radioButton_mi.id = radio_group.checkedRadioButtonId这两行代码。
  2. 改用整数保存单位ID:将saveUnitData中的putFloat改为putInt,loadUnitData中的getFloat改为getInt,并设置合理的默认值(比如默认选中km)。
  3. 同步选中状态:在onCreate和onResume中调用radioGroup.check(unit),确保加载数据后选中状态正确显示。
  4. 调整视图初始化顺序:先初始化所有视图,再加载数据并恢复状态,避免空指针或状态未同步的问题。
  5. 修正onResume逻辑:移除错误的unit = radio_group.checkedRadioButtonId,改为重新恢复选中状态。

这样修改后,计量单位的选中状态就能正确持久化和恢复了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 18:27:22