使用Android导航将数据传回上一个片段 [英] Pass data back to previous fragment using Android Navigation

查看:888
本文介绍了使用Android导航将数据传回上一个片段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经开始使用Android体系结构组件(导航和安全Args,视图模型)以及Koin库.

I've started using Android Architecture Components (Navigation and Safe Args, View Models) along with Koin library.

当前,我在两个片段之间传递参数时遇到了问题-我需要将一个字符串值从片段A传递到片段B,在片段B中修改此值,然后将其传递回片段A.

Currently, I've got a problem with passing arguments between two fragments - I need to pass a string value from fragment A to fragment B, modify this value in fragment B and pass it back to fragment A.

我找到了解决我的问题的一种可能的方法-共享视图模型.不幸的是,这种方法有一个问题,因为我可以在屏幕之间传递和修改值,但是当片段A导航到另一个目标时,共享视图模型中的值仍会存储而不清除.

I've found one possible solution to my problem - shared view models. Unfortunately, this approach has one problem because I can pass and modify values between screens, but when the fragment A navigate to another destination the value in the shared view model is still stored and not cleared.

在Android导航中的片段之间传递和修改数据是否有其他解决方案?我想避免手动清除此值(当碎片A被破坏时).

Is there any different solution of passing and modifying data between fragments in Android Navigation? I want to avoid clearing this one value by hand (when the fragment A is destroyed).

推荐答案

Android刚刚为此发布了一个解决方案. 在目标之间传递数据(导航2.3.0-alpha02 ),基本上,在片段A中您会观察到变量的变化,而在片段B中您会在执行popBackStack()之前更改该值.

Android just released a solution for this; Passing data between Destinations (Navigation 2.3.0-alpha02), basically, in fragment A you observe changes in a variable and in fragment B you change that value before executing popBackStack().

片段A:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
val navController = findNavController();
// We use a String here, but any type that can be put in a Bundle is supported
navController.currentBackStackEntry?.savedStateHandle?.getLiveData("key")?.observe(
    viewLifecycleOwner) { result ->
    // Do something with the result.
  }
}

片段B:

navController.previousBackStackEntry?.savedStateHandle?.set("key", result)
navController.popBackStack()

这篇关于使用Android导航将数据传回上一个片段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆