【发布时间】:2022-01-16 22:00:02
【问题描述】:
我的片段中recyclerview中的数据使用了网站的api。但是切换底部导航时数据丢失。但数据结构不是简单的 int 或 string。我应该如何将它写入 onSaveInstanceState 来存储它。以及如何让他正常恢复LiveData的数据类型?
recyclerview 的数据看起来像 viewmodel 中的那样。
private val _photos = MutableLiveData<List<SportData>>()
val photos: LiveData<List<SportData>> get() = _photos
数据类
@Parcelize
data class SportData (
val GymID:Int,
val Photo1:String,
val Name:String,
val Address:String,
val OperationTel:String,
val OpenState:String,
val GymFuncList:String
): Parcelable
我尝试将数据保存在 onDestroyView() 中并在 onViewCreated 中获取它。它以 null 失败。
override fun onDestroyView() {
photos2=viewModel.photos
super.onDestroyView()
Log.d("aaa","destroyVIEW and ${photos2}")
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
Log.d("aaa","=viewCreate and ${photos2}")
if (photos2!=null){
viewModel.saveData(photos2!!)
}
视图模型
fun saveData(savePhoto:LiveData<List<SportData>>){
_photos=savePhoto as MutableLiveData<List<SportData>>
}
你好,你能帮帮我吗?谢谢
【问题讨论】:
-
您是否考虑过在下载对象后将其保存在数据库中并使用它将数据呈现给 ui 层?
-
当前不保存房间数据。
-
你明白
onSaveInstanceState应该做什么吗?我想不出您需要使用它来备份 ViewModel 中的数据的任何原因。 ViewModel 将在配置更改期间比 Fragment 寿命更长,因此保存实例状态是没有意义的。 -
我还以为是因为底部导航开关而丢失了fragment recyclerview数据。我可以用它来保存它。那么如何让fragment还是切换底部导航后刚看到的画面呢?
-
您在使用导航组件吗?您使用的是 Navigation 2.4(当前为 2.4.0-rc01)吗?只有 Navigation 2.4 会保存和恢复每个底部导航项的状态。
标签: android kotlin android-recyclerview