问题
I found the question but does not have solution in code
I want to have data when backpress/manual back happens. I am using navigateUp()
to go back. How can I pass data to previous fragment? navigateUp()
does not have any facility to pass data to previous fragment. Even I did not find solution using Safe Args. It's passing data forward. I want to have in backward Frad B -> Frag A.
My code to go back to previous fragment
Navigation.findNavController(view).navigateUp()
My question is, How can i get data in previous fragment. I can navigate to Frag A from Frag B using
回答1:
According to developer.android.com, you can use common for fragments where you want to share data ViewModel using their activity scope.
Here are steps:
- Create view model which will keep the data:
class SharedViewModel : ViewModel() {
val dataToShare = MutableLiveData<String>()
fun updateData(data: String) {
dataToShare.value = data
}
}
- Observe data changes in Fragment1:
class Fragment1 : Fragment() {
private lateinit var viewModel: SharedViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel = ViewModelProviders.of(activity!!).get(SharedViewModel::class.java)
viewModel.dataToShare.observe(this, Observer<String> { dataFromFragment2 ->
// do something with data
})
}
}
- Update data in
Fragment2
and if you're handling navigation properly, now, you should be able to receive data changes onFragment1
:
class Fragment2 : Fragment() {
private lateinit var viewModel: SharedViewModel
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
viewModel = ViewModelProviders.of(activity!!).get(SharedViewModel::class.java)
updateDataButton.setOnClickListener { v ->
viewModel.updateData("New data for fragment1")
}
}
}
I hope answer helps.
回答2:
You can NavigationResult library. Basically it's startActivityForResult
but for Fragments in Navigation component.
回答3:
You can just call
findNavController().navigate(R.id.fragment1, args)
where args is your bundle. In fragment1, fetch the data from the arguments
来源:https://stackoverflow.com/questions/55058689/pass-data-bundle-using-navigateup-in-android-navigation-component