4

I am using a BottomSheetDialogFragment class with Navigation Architecture component. I am following the Single activity pattern and therefore i have only one activity and several fragments. Below is my code.

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
}
}

And this is how i open the dialog in my navigation.xml from my main fragment:

    <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" />

Now i want to pass data FROM the bottom sheet to the main fragment.

Is there a proper way to do this? Can someone please help me.

Thank you.

4

1 回答 1

9

Navigation2.3.0-alpha02开始,Navigation 已内置支持将结果返回到先前的目的地。

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

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

请注意,有一些DialogFragment 特定的注意事项需要牢记 - 因为RESUMED即使BottomSheetFragment显示前一个片段,结果也会立即发送到您的第一个片段。

于 2020-04-19T19:28:54.230 回答