Reputation: 414
so I'm using the navigation component and something I'm trying to do right now is implement a listener for when the user clicks a button in a dialog. In another fragment, I want to detect when that happens.
In the past, I would just create an interface within the dialog and call the interface's function in the button's onClick. Then in the fragment, I'd set the listener by having a variable for the dialog and calling the set function, with the interface function implemented in the fragment. So like:
dialogFrag.setListener(this)
But with navigation component, I'm not sure how to do this since I've been handling navigation like:
findNavController().navigate(R.id.dialogName)
Any idea how to do this?
Upvotes: 4
Views: 1269
Reputation: 1322
as mentioned here I will duplicate his solution
Android navigation architecture component
eg:
Suppose you open Fragment B from Fragment A using navController.
and you want some data from fragment B to Fragment A.
class B :BottomSheetDialogFragment() {
override fun onCreateView(
inflater: LayoutInflater, container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
val root = inflater.inflate(R.layout.your_layout, container, false)
root.sampleButton.setOnClickListener {
val navController = findNavController()
navController.previousBackStackEntry?.savedStateHandle?.set("your_key", "your_value")
dismiss()
}
}
and in your Fragment A:
findNavController().currentBackStackEntry?.savedStateHandle?.getLiveData<String>("your_key")
?.observe(viewLifecycleOwner) {
if (it == "your_value") {
//your code
}
}
Upvotes: 1