Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to pass a value back to previous fragment destination using Android navigation component?

let sat I have some destinations like this

from fragment A --> to fragment B --> to fragment C

I can use Safe Args to pass data from fragment A to fragment B. and also using safe args from fragment B to fragment C.

what if I want to bring a string that generated in fragment C back to fragment B or to fragment A ?

to navigate from fragment C to fragment B, I use code:

Navigation.findNavController(fragmentView).navigateUp()

and to navigate from fragment C to fragment A, I use code:

Navigation.findNavController(view).popBackStack(R.id.fragmentA, false)

so how to pass a value back to previous fragment destination ? do I have to make an action back from fragment C to fragment B and pass the value through safe args ?

really need your help. Thank you very much :)

like image 571
Alexa289 Avatar asked Aug 18 '19 01:08

Alexa289


1 Answers

You can use the below snippet for sending data to previous fragment.

Fragment A observing the data:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    findNavController().currentBackStackEntry?.savedStateHandle?.getLiveData<String>("key")?.observe(viewLifecycleOwner) { data ->
        // Do something with the data.
    }
}

Fragment B sending the data:

findNavController().previousBackStackEntry?.savedStateHandle?.set("key", data)
findNavController().popBackStack()

I also wrote extensions for this.

fun <T : Any> Fragment.setBackStackData(key: String,data : T, doBack : Boolean = true) {
    findNavController().previousBackStackEntry?.savedStateHandle?.set(key, data)
    if(doBack)
    findNavController().popBackStack()
}

fun <T : Any> Fragment.getBackStackData(key: String, result: (T) -> (Unit)) {
    findNavController().currentBackStackEntry?.savedStateHandle?.getLiveData<T>(key)?.observe(viewLifecycleOwner) {
        result(it)
    }
}

Usage:

Fragment A:

getBackStackData<String>("key") { data ->
    // Do something with the data.
}

Fragment B:

setBackStackData("key",data)

    

Note: I am using String as data. You may use any other type of variable.

Note: If you are going to use a Class as data, don't forget to add @Parcelize annotation and extend Parcelable.

like image 97
Amir Avatar answered Oct 24 '22 04:10

Amir