Fragment中的LifecycleOwners必须在STARTED之前调用register错误:如何修复?
你好!我正在使用Android Jetpack开发Kotlin应用,遇到了一个令人困惑的错误。
我有一个Fragment,在其中使用`LifecycleObserver`来跟踪生命周期状态。我在`onViewCreated()`方法中注册了观察者:
```kotlin
class MyFragment : Fragment() {
override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
super.onViewCreated(view, savedInstanceState)
lifecycle.addObserver(MyObserver())
}
}
class MyObserver : LifecycleObserver {
@OnLifecycleEvent(Lifecycle.Event.ON_START)
fun onStart() {
Log.d("MyObserver", "Fragment is started")
}
}
```
一切正常,直到我开始在Fragment之间切换或最小化/恢复应用。然后我得到:
```
java.lang.IllegalStateException: LifecycleOwners must call register before they are STARTED.
```
我阅读了文档,但不太明白为什么