android - 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()
}
解决方案
您可以使用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) {
}
}
推荐阅读
- ios - 如何在 iOS 中更新 XLPagerTabStrip 的指标信息?
- oracle10g - ODI 10g 中的哪个表存储有关启动的所有会话的详细信息
- java - Selenium 在单击添加文件按钮时打开新窗口
- android - 使用 imageview 突出显示 android 应用程序中的新功能并使其在 1 次单击后看起来正常?
- slurm - 检索作业提交限制
- javascript - 如何突出显示表格列?
- php - 提交到下拉列表并显示所选值后如何保留ajax数据?
- python - Pandas 在第三个分隔符实例后拆分列?
- ios - Firebase Crashlytics for Swift 上未显示的实际原因
- linux - 如何通过特定的网络接口发送?