[英]Android: Update Fragment A when user hits back on Fragment B in Navigation Component, Single activity app
I have the following requirement: Fragment A shows all referred friends from API call, which it calls onCreateView.我有以下要求:片段 A 显示来自 API 调用的所有推荐朋友,它调用 onCreateView。 The user can navigate from Fragment A -> Fragment B. In Fragment B the user can refer new friends.
用户可以从 Fragment A -> Fragment B 导航。在 Fragment B 中,用户可以推荐新朋友。 When the user refers a friend I make an API call and trigger activity.onBackPressed() to pop Back to Fragment A.
当用户推荐朋友时,我调用 API 并触发 activity.onBackPressed() 以弹出返回片段 A。
On return in Fragment A, I need to make the API call to get all referred friends to update the UI.在片段 A 中返回时,我需要调用 API 来让所有推荐的朋友更新 UI。 Unfortunately neither onCreateView() nor onResume() nor onStart() are called when I pop back.
不幸的是,当我弹回时,既不调用 onCreateView() 也不调用 onResume() 或 onStart()。 How do I make the new API call and update the UI?
如何进行新的 API 调用并更新 UI?
Fragment A:片段 A:
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
viewModel = ViewModelProvider(this).get(ReferAFriendViewModel::class.java)
viewModel.getRAFStatus().observe(viewLifecycleOwner,{
//UpdateUI
})
} }
Fragment B:片段 B:
viewModel.postSendInvites(binding.etName.text.toString(), binding.etEmail.text.toString())
requireActivity().onBackPressed()
You can use this in your first fragment.你可以在你的第一个片段中使用它。
findNavController().currentBackStackEntry?.savedStateHandle?.getLiveData<Type>("key")?.observe(
viewLifecycleOwner) {result ->
// Do something with the result.
}
And in your second fragment.在你的第二个片段中。
findNavController().previousBackStackEntry?.savedStateHandle?.set("key", result)
I end up creating two extension functions for it.我最终为它创建了两个扩展函数。
fun <T> Fragment.getCurrentBackStackEntryLiveData(key: String): MutableLiveData<T>? {
return findNavController().currentBackStackEntry?.savedStateHandle?.getLiveData(key)
}
fun <T> Fragment.setCurrentBackStackEntryLiveData(key: String, value: T) {
findNavController().previousBackStackEntry?.savedStateHandle?.set(key, value)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.