将数据从底部工作表对话框片段传递到片段

Mer*_*aju 4 android kotlin android-architecture-navigation android-bottomsheetdialog

我正在使用带有导航架构组件的 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
}
}
Run Code Online (Sandbox Code Playgroud)

这就是我从主片段打开 navigation.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" />
Run Code Online (Sandbox Code Playgroud)

现在我想将数据从底部工作表传递到主要片段。

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

谢谢你。

ian*_*ake 9

Navigation 开始2.3.0-alpha02, Navigation 内置了对将结果返回到先前目的地的支持。

这分为两部分,您的第一个片段(想要接收结果的片段)将用于在 NavController 中navController.currentBackStackEntry?.savedStateHandle获取对其SavedStateHandle关联NavBackStackEntry的引用。然后,它可以observe通过特定的键在该键更改时获得回调。

第二个片段(传递结果的片段,即您的LogoBottomSheetFragment)将SavedStateHandle通过使用navController.previousBackStackEntry?.savedStateHandle. 当第二个片段调用setSavedStateHandle,该结果可用于第一个片段。

请注意,有一些DialogFragment 特定的注意事项需要记住 - 因为前一个片段在显示RESUMED时是均匀的BottomSheetFragment,结果将立即发送到您的第一个片段。