Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android Navigation Component - Implementing Listener

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?

like image 779
daniel-eh Avatar asked Dec 06 '25 06:12

daniel-eh


1 Answers

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
    
                    }
    
                }
like image 50
Amr Avatar answered Dec 07 '25 20:12

Amr



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!