从底部弹出的对话框片段传递数据到片段

5

我正在使用带有导航架构组件的BottomSheetDialogFragment类。我遵循单一活动模式,因此只有一个活动和多个片段。以下是我的代码。

BottomSheetDialogFragment.kt

class LogoBottomSheetFragment : BottomSheetDialogFragment() {

private var _binding: FragmentBottomSheetAccountLogoBinding? = null
private val binding get() = _binding!!

override fun onCreateView(
    inflater: LayoutInflater,
    container: ViewGroup?,
    savedInstanceState: Bundle?
): View? {
    _binding = FragmentBottomSheetAccountLogoBinding.inflate(inflater, container, false)

    return binding.root
}

override fun onDestroyView() {
    super.onDestroyView()
    _binding = null
}
}

这是我从主片段打开导航.xml中对话框的方法:

    <dialog
    android:id="@+id/logoBottomSheetFragment"
    android:name="com.th3pl4gu3.locky.ui.main.add.account.LogoBottomSheetFragment"
    android:label="LogoBottomSheetFragment"
    tools:layout="@layout/fragment_bottom_sheet_account_logo" />

现在我想要从底部表单传递数据到主碎片。

有没有合适的方法可以做到这一点?请有人能帮帮我吗。

谢谢。


2
你有没有阅读最近添加的返回结果文档 - ianhanniballake
这对我的情况来说太完美了!非常感谢你提供这个。我之前不知道有这种解决方法。 - Mervin Hemaraju
1个回答

10
截至 导航2.3.0-alpha02,导航内置支持返回到先前的目的地的功能。
这个功能有两个部分组成。首先,想要接收结果的第一个片段将使用navController.currentBackStackEntry?.savedStateHandle来获取与其在NavController中的NavBackStackEntry相关联的SavedStateHandle的引用。然后,它可以观察特定的键以在该键更改时获得回调。
第二个片段(即传递结果的片段,例如您的LogoBottomSheetFragment)将通过使用navController.previousBackStackEntry?.savedStateHandle来获取完全相同的SavedStateHandle的引用。当第二个片段在SavedStateHandle上调用set时,该结果就可供第一个片段使用。
请注意,有一些DialogFragment特定的考虑因素需要记住 - 因为前一个片段即使在显示BottomSheetFragment时处于RESUMED状态,结果也会立即发送到您的第一个片段。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接