简体   繁体   中英

Save Fragment data when switch to another fragment using Navigation

I just started with my first Android project. 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. 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. So I did a little test, turns out the onSaveInstanceState() is not even being called when I switch the fragment. Instead, onDestroy() and onPause() are being called, ones where people don't recommend to save my data

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.

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM