简体   繁体   English

使用导航切换到另一个片段时保存片段数据

[英]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.

相关问题 使用底部导航栏从一个片段移动到另一个片段时重置数据 - Data reset when moving from one to another fragment using Bottom Navigation Bar 无法使用导航情节提要板在片段中添加按钮以从一个片段跳转到另一个片段 - Unable to add a button in fragment using Navigation storyboard to jump from one fragment to another fragment 使用导航抽屉保存片段状态 - Save fragment state with navigation drawer 更改BottomNavigationView中的片段时如何保存数据? - How to save data when fragment in BottomNavigationView is changed? 在另一个片段中更改数据时如何刷新一个片段中的RecyclerView - How to refresh RecyclerView in one fragment when data changed in another fragment 调用时加载片段,并在切换到另一个片段/活动时保留 - Load fragments when call it and keep when switch to another fragment/activity 如何使用 java 将数据从片段传递到 android 中的另一个片段? - How to pass data from fragment to another fragment in android using java? 如何在更改片段上保存片段回收视图数据? - How to save Fragment recyclerview data on change fragment? 底部导航栏在打开另一个片段时停止运行 - Bottom navigation bar stop a fragment running when another one is opened 在Android Studio中,如何使用Java代码将片段切换到另一个片段 - In Android Studio, how do you switch a fragment to another fragment using java code
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM