Pass data from Bottom Sheet Dialog Fragment to Fragment
Asked Answered
T

1

5

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.

Tennyson answered 19/4, 2020 at 16:19 Comment(2)
Did you read the Returning a result documentation that was recently added?Syntax
This is just perfect for my situation! Thank you so much for this. I was not aware of this workaround.Tennyson
S
11

As of Navigation 2.3.0-alpha02, Navigation has built in support for Returning a result to a previous destination.

This works in two parts, your first fragment (the one wanting to receive the result) would use navController.currentBackStackEntry?.savedStateHandle to get a reference to the SavedStateHandle associated with its NavBackStackEntry in the NavController. Then, it can observe a particular key to get a callback whenever that key changes.

The second fragment (the one delivering the result, i.e., your LogoBottomSheetFragment) would get a reference to that exact same SavedStateHandle by using navController.previousBackStackEntry?.savedStateHandle. When that second fragment calls set on the SavedStateHandle, that result is then made available for the first fragment.

Note that there are some DialogFragment specific considerations to keep in mind - because the previous fragment is RESUMED even when the BottomSheetFragment is being shown, the result will instantly be sent to your first fragment.

Syntax answered 19/4, 2020 at 19:28 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.