【发布时间】:2020-06-10 19:38:32
【问题描述】:
我正在使用导航组件,我有 Fragment A 和 Fragment B,从 Fragment A 我发送一个对象到 带有安全参数的片段 B 并导航到它。
override fun onSelectableItemClick(position:Int,product:Product) {
val action = StoreFragmentDirections.actionNavigationStoreToOptionsSelectFragment(product,position)
findNavController().navigate(action)
}
现在,在我的 Fragment B 中的一些逻辑之后,我想再次将该数据传递给 Fragment A,我使用它
btn_add_to_cart.setOnClickListener {button ->
findNavController().previousBackStackEntry?.savedStateHandle?.set("optionList",Pair(result,product_position))
findNavController().popBackStack()
}
然后在Fragment A中,我用
赶上了这些数据findNavController().currentBackStackEntry?.savedStateHandle?.getLiveData<Pair<MutableList<ProductOptions>,Int>>("optionList")
?.observe(viewLifecycleOwner, Observer {
storeAdapter.updateProductOptions(it.second,it.first)
})
现在,这工作正常,但如果我从 Fragment A 转到 Fragment B 并按下后退按钮,上面的观察者会再次触发复制我当前的数据,当我只按下 Fragment B 中的btn_add_to_cart 按钮时,有没有办法触发这个观察者?
【问题讨论】:
-
使用单一事件解决您的问题,您可以参考:proandroiddev.com/livedata-with-single-events-2395dea972a8
标签: android android-fragments kotlin android-viewmodel android-architecture-navigation