我有三个fragments
,它们使用新的导航组件版本,在其中您可以共享连接到某些流的ViewModel
。
无论如何,第三个fragment
可以导航回到第一个,我需要清除ViewModel
我已经检查了this的答案,但是由于某种原因,viewModelStore.clear()
并没有清除任何内容
第一个片段:
class FirstFragment : Fragment() {
private val viewModel: ShareViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
//it does nothing
viewModelStore.clear()
}
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
//here the lpn must be null
vehicle_lpn.text = (vehicle_lpn.text as String).plus(viewModel.vehicleLpn.value)
button.setOnClickListener {
viewModel.setVehicleLpn("Hey")
findNavController().navigate(R.id.action_firstFragment_to_secondFragment)
}
}
}
第二个片段:
class SecondFragment : Fragment() {
private val viewModel: ShareViewModel by navGraphViewModels(R.id.navigation_main)
}
第三片段:
class ThirdFragment : Fragment() {
private val viewModel: ShareViewModel by navGraphViewModels(R.id.navigation_main)
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
vehicle_lpn.text = "VEHICLE LPN: " + viewModel.vehicleLpn.value
button.setOnClickListener { findNavController().navigate(R.id.action_thirdFragment_to_firstFragment) }
}
}