首页 > 解决方案 > How to make set TextView.text persistent in Android app (Kotlin)

问题描述

I am currently trying to make a TextView show whatever date my TimePicker returns. It works, but if I go into another fragment and back, restart the app, etc, the text reverts to the default I set. Does anyone know how I could make the text I'm setting persistent? Here is the code that I am using.

view.timeButton.setOnClickListener {
            val cal = Calendar.getInstance()
            val timeSetListener = TimePickerDialog.OnTimeSetListener { timePicker, hour, minute ->
                cal.set(Calendar.HOUR_OF_DAY, hour)
                cal.set(Calendar.MINUTE, minute)

                alarmText.text = ("Texts at " + SimpleDateFormat("HH:mm").format(cal.time))
            }
            TimePickerDialog(
                context,
                timeSetListener,
                cal.get(Calendar.HOUR_OF_DAY),
                cal.get(Calendar.MINUTE),
                false
            ).show()
        }

标签: androidkotlin

解决方案


您可以使用SharedPreference永久保存它

view.timeButton.setOnClickListener {
            val cal = Calendar.getInstance()
            val timeSetListener = TimePickerDialog.OnTimeSetListener { timePicker, hour, minute ->
                cal.set(Calendar.HOUR_OF_DAY, hour)
                cal.set(Calendar.MINUTE, minute)

                val simpleDateFormat = SimpleDateFormat("HH:mm")
                val date = simpleDateFormat.format(cal.time)
                alarmText.text = ("Texts at " + date)

                val preferences: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
                preferences.edit().putString("mydate", date).apply();
                
            }
            TimePickerDialog(
                context,
                timeSetListener,
                cal.get(Calendar.HOUR_OF_DAY),
                cal.get(Calendar.MINUTE),
                false
            ).show()
        }

并在您的应用程序中onCreate检索存储的值

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
        try {
            val preferences: SharedPreferences = PreferenceManager.getDefaultSharedPreferences(this)
            val simpleDateFormat = SimpleDateFormat("HH:mm")
            val date: Date = simpleDateFormat.parse(preferences.getString("mydate", ""))
            alarmText.text = ("Texts at " + date)
        }
        catch (e: ParseException) {
        }
    }

推荐阅读