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

Kotlin中返回上一Activity时如何保存TextView中的数值

解决方案:保存子Activity数值直至重置

问题背景

我有一个子Activity,包含递增、递减按钮,希望返回父Activity时保留数值,直到点击重置按钮清空。试过SharedPreference但误以为它仅适用于主到二级Activity的场景,Activity Result对我来说难度过高。

核心思路

SharedPreferences是最适合这个需求的方案——它能轻松实现数值的持久化存储,完全适配子Activity的场景。只需做以下几点:

  • 子Activity启动时读取已保存的数值
  • 数值变化时实时保存
  • 添加重置按钮清空存储的数值

修改后的代码

父Activity(TallBoys.kt)

简化重复的按钮点击逻辑,补全btn1的启动代码:

import android.content.Intent
import android.os.Bundle
import android.widget.Button
import androidx.appcompat.app.AppCompatActivity

class TallBoys : AppCompatActivity() {

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

        // 批量获取按钮,简化重复代码
        val buttons = listOf(
            findViewById<Button>(R.id.button1),
            findViewById(R.id.button2),
            findViewById(R.id.button3),
            findViewById(R.id.button4),
            findViewById(R.id.button5),
            findViewById(R.id.button6),
            findViewById(R.id.button7)
        )

        // 给所有按钮设置统一的跳转逻辑
        buttons.forEach { btn ->
            btn.setOnClickListener {
                startActivity(Intent(this, TallBoysNumbers::class.java))
            }
        }
    }
}

子Activity(TallBoysNumbers.kt)

添加SharedPreferences读写逻辑与重置功能:

import android.os.Bundle
import android.widget.Button
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import android.content.SharedPreferences

class TallBoysNumbers : AppCompatActivity() {
    private val COUNT_SAVE_KEY = "saved_tall_boys_count"
    private lateinit var sharedPref: SharedPreferences
    private var count = 0

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

        // 初始化专属当前Activity的SharedPreferences
        sharedPref = getPreferences(MODE_PRIVATE)

        val confirmBtn: Button = findViewById(R.id.confirm_button)
        val plusBtn: Button = findViewById(R.id.plus)
        val textView: TextView = findViewById(R.id.numbers)
        val negBtn: Button = findViewById(R.id.negative)
        val resetBtn: Button = findViewById(R.id.reset_button) // 需在布局中添加该按钮

        // 读取已保存的数值,无数据则默认0
        count = sharedPref.getInt(COUNT_SAVE_KEY, 0)
        textView.text = count.toString()
        // 初始化按钮可用状态
        updateButtonStates()

        plusBtn.setOnClickListener {
            count++
            textView.text = count.toString()
            updateButtonStates()
            saveCurrentCount()
        }

        negBtn.setOnClickListener {
            count--
            textView.text = count.toString()
            updateButtonStates()
            saveCurrentCount()
        }

        resetBtn.setOnClickListener {
            count = 0
            textView.text = count.toString()
            updateButtonStates()
            // 清空存储的数值
            sharedPref.edit().remove(COUNT_SAVE_KEY).apply()
        }

        confirmBtn.setOnClickListener {
            finish()
        }
    }

    // 统一更新按钮可用状态,避免重复代码
    private fun updateButtonStates() {
        val plusBtn: Button = findViewById(R.id.plus)
        val negBtn: Button = findViewById(R.id.negative)
        plusBtn.isEnabled = count < 8
        negBtn.isEnabled = count > 0
    }

    // 封装数值保存逻辑
    private fun saveCurrentCount() {
        sharedPref.edit().putInt(COUNT_SAVE_KEY, count).apply()
    }
}

关键说明

  1. SharedPreferences适配性:getPreferences(MODE_PRIVATE)创建的是当前子Activity专属的存储文件,不会和其他Activity的存储冲突,完全符合需求。
  2. 实时持久化:每次点击加减按钮都调用saveCurrentCount(),确保数值变化后立即保存,返回父Activity再打开时能直接读取最新值。
  3. 重置功能:点击重置按钮时,不仅将界面数值归零,还会删除SharedPreferences中的存储项,下次启动子Activity时会回到初始状态。
  4. 代码优化:把重复的按钮状态更新逻辑抽成独立方法,让代码更简洁易维护。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.06 19:25:16