简体   繁体   English

使用 OnBackPressedCallback 向后传递可打包包

[英]Passing a parcelable bundle backwards using the OnBackPressedCallback

In my app I am using the OnBackPressedCallback and calling the findNavController.popBackStack to manage backwards navigation.在我的应用程序中,我使用 OnBackPressedCallback 并调用 findNavController.popBackStack 来管理向后导航。 One limitation I have encountered is that I cannot find a way to pass a parcelable bundle back when the user clicks the back button.我遇到的一个限制是,当用户单击后退按钮时,我无法找到一种将可打包捆绑包传回的方法。

The use case is simple: Fragment A user inputs some data.用例很简单:片段 A 用户输入了一些数据。 It's passed along to Fragment B the user inputs some more data.它被传递给片段 B,用户输入更多数据。 User decides they want to go back to Fragment A and edit previous data so I want to pass the bundle back so they dont lose the data previously inputted.用户决定他们要返回片段 A 并编辑以前的数据,因此我想将捆绑包传回去,这样他们就不会丢失以前输入的数据。

Using the Navigation component I could simply attach the bundle when navigating back but using this OnBackPressCallback we do not use the navigation component, thus there is nothing to attach a bundle to.使用 Navigation 组件,我可以在导航回时简单地附加包,但使用此 OnBackPressCallback 我们不使用导航组件,因此没有什么可以附加包。

Does anyone have any potential simple solutions to this?有没有人对此有任何潜在的简单解决方案? I have already considered SharedPreferences however I am passing an object and SP only allows primatives.我已经考虑过 SharedPreferences 但是我正在传递一个对象并且 SP 只允许原始类型。

The simplest solution would be to serialise your parcelable into a JSON string, save it to shared preferences then de-serialise it when you need to retrieve that data.最简单的解决方案是将 Parcelable 序列化为 JSON 字符串,将其保存到共享首选项,然后在需要检索该数据时将其反序列化。

There are 2 well-known and reliable JSON libraries, if you're not already using one or are not familiar with it: you can use either Gson (Google) or Moshi (Square)有 2 个众所周知且可靠的 JSON 库,如果您还没有使用或不熟悉它:您可以使用 Gson (Google) 或 Moshi (Square)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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