[英]Save Fragment data when switch to another fragment using Navigation
I just started with my first Android project.我刚开始我的第一个 Android 项目。 My application contains two fragments that are connected with the navigation controller.我的应用程序包含两个与导航控制器相连的片段。
As for now, all I have on my first fragment is only two EditText.至于现在,我在第一个片段上只有两个 EditText。 However, I realize that when I switch to my other fragment and navigate back, the texts entered have been cleared.但是,我意识到当我切换到另一个片段并返回时,输入的文本已被清除。
So I would like to know what I can do to save the date and restore them when I switch it back所以我想知道我可以做些什么来保存日期并在我切换回来时恢复它们
I have already tried saving them in onSaveInstanceState() as suggested by the majority of people, however, it is not working.我已经按照大多数人的建议尝试将它们保存在onSaveInstanceState()中,但是,它不起作用。 So I did a little test, turns out the onSaveInstanceState() is not even being called when I switch the fragment.所以我做了一个小测试,结果发现当我切换片段时甚至没有调用onSaveInstanceState() 。 Instead, onDestroy() and onPause() are being called, ones where people don't recommend to save my data相反,正在调用onDestroy()和onPause() ,人们不建议保存我的数据
I have also tried to use ViewModel to save the data but it seems that the data saved into the ViewModel is also gone when I switch back to the original Fragment.我也尝试过使用ViewModel来保存数据,但是当我切换回原始Fragment时,保存到ViewModel中的数据似乎也没有了。
So I am not sure what to do?所以我不知道该怎么办? Thanks!谢谢!
您应该使用 ViewModel,在您的 Fragment.onViewCreated() 方法中通过 Activity 而不是 Fragment 创建您的 ViewModel
val myViewModel = ViewModelProvider(activity as ViewModelStoreOwner).get(MyViewModel::class.java)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.