Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass data from Bottom Sheet Dialog Fragment to Fragment

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.

like image 939
Mervin Hemaraju Avatar asked Jan 01 '23 03:01

Mervin Hemaraju


1 Answers

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.

like image 83
ianhanniballake Avatar answered Jan 02 '23 17:01

ianhanniballake