[英]Android How Lifecycle-Aware Components Detect Configuration Change inside ViewModel
My Fragment
:我的Fragment
:
class FirstFragment : Fragment() {
private lateinit var binding: FragmentFirstBinding
private lateinit var viewModelFactory: FirstViewModelFactory
private lateinit var viewModel: FirstViewModel
override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View {
binding = DataBindingUtil.inflate(inflater, R.layout.fragment_first, container, false)
viewModelFactory = FirstViewModelFactory(requireActivity().application, this.lifecycle) //<- Lifecycle object
viewModel = ViewModelProvider(this, viewModelFactory).get(FirstViewModel::class.java)
return binding.root
}
}
My ViewModel:
我的ViewModel:
class FirstViewModel(application: Application, lifecycle: Lifecycle) : AndroidViewModel(application), LifecycleObserver {
init {
lifecycle.addObserver(this)
}
@OnLifecycleEvent(Lifecycle.Event.ON_STOP)
private fun showOnStopMessage() {
Log.v("xxx", "onStop called!!")
}
@OnLifecycleEvent(Lifecycle.Event.ON_START)
private fun showOnStartMessage() {
Log.v("xxx", "onStart called!!")
}
}
The above setup works well in no-configuration-change environment, showOnStopMessage()
gets called when app goes to the background, and showOnStartMessage()
gets called when the app is brought back to the foreground.上述设置在无配置更改环境下运行良好,当应用程序进入后台时调用showOnStopMessage()
showOnStartMessage()
,当应用程序返回前台时调用 showOnStartMessage()。
The problem is, when configuration-change happens (like rotating the screen), those functions are not being called any more.问题是,当配置更改发生时(如旋转屏幕),这些函数不再被调用。
Why this happens?为什么会发生这种情况? How to detect and "survive" configuration-change?如何检测和“生存”配置更改? Thanks in advance.提前致谢。
As far as I understand, the problem is that your ViewModel is created only once (as it should be) and it only adds the lifecycle of the first fragment as a LifecycleObserver.据我了解,问题在于您的 ViewModel 仅创建一次(应该如此),并且它仅将第一个片段的生命周期添加为 LifecycleObserver。 When you rotate the screen, the same ViewModel is returned and it'll still try to react to the changes of the old Fragment, which won't happen.当您旋转屏幕时,会返回相同的 ViewModel,它仍会尝试对旧 Fragment 的更改做出反应,这不会发生。
I'd suggest not dealing with lifecycle inside the ViewModel at all (remove the related code from the Factory and from the ViewModel).我建议根本不处理 ViewModel 中的生命周期(从 Factory 和 ViewModel 中删除相关代码)。 Just call:只需致电:
lifecycle.addObserver(viewModel)
right after the ViewModel is obtained, inside onCreateView.在获得 ViewModel 之后,在 onCreateView 中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.