当前位置: 代码迷 >> 综合 >> android学习笔记:activity(7)-fragment lifecycle
  详细解决方案

android学习笔记:activity(7)-fragment lifecycle

热度:19   发布时间:2023-11-20 22:20:13.0

1.To manage lifecycle,Fragment implements(实现)LifecycleOwner,exposing a Lifecycle object that you can access through the getLifecycle() method.

2.The onAttach() callback is invoked(调用) when the fragment has been added to a FragmentManager and is attached(附属的) to its host(主) activity.onAttach() is always called before any Lifecycle state changes

3.The onDetach() callback is invoked when the fragment has been removed from a FragmentManager and is detached(分离) from its host activity.onDetach() is always called after any Lifecycle state changes

4.note that these callbacks are unrelated to the FragmentTransaction methods attach() and detach()

5.避免在片段实例从FragmentManager中删除后重用它们。当片段处理自己的内部状态清理时,您可能会无意中将自己的状态带入重用实例。

6.A fragment's maximum(最大状态) state is determined by its FragmentManager.A fragment cannot progress beyond the state of its FragmentManager.

7.As part of a FragmentTransaction, you can set a maximum lifecycle state on a fragment using setMaxLifecycle()

8.A fragment's lifecycle state can never be greater than its parent.For example,a parent fragment or activity must be started before its child fragments.Likewise(同样的),child fragments must be stopped before their parent fragment or activity

9.Caution:Avoid vsing the<fragment>tag to add a fragment using XML,as the <fragment>tag allwos a fragment to move beyond the state of its FragmentManager.Instead,always use FragmentContainerView for adding a fragment using XML.

10.Each possible Lifecycle state is represented in the Lifecycle State enum

INITIALIZED,CREATED,STARTED,RESUMED,DESTORYED

11.The Fragment class includes callback methods that correspond to each of the changes in a fragment's lifecycle.These include onCreate(),onStart(),onResume(),onPause(),onStopr()and onDestory()

12.fragment的视图有一个独立的生命周期,该生命周期独立于片段的生命周期进行管理.Fragments maintain a LifecycleOwner for their view,which can be accessed using getViewLifecycleOwner() or getViewLifecycleOwnerLiveData(),

 10.当片段达到创建状态时,它已被添加到FragmentManager,并且已调用了onAttach()方法。
这将是通过片段的SavedStateRegistry恢复与片段本身关联的任何保存状态的适当位置。请注意,此时尚未创建片段的视图,只有在创建视图后,才应恢复与片段视图关联的任何状态。
此转换调用onCreate()回调。回调还接收一个savedInstanceState包参数,该参数包含onSaveInstanceState()以前保存的任何状态。请注意,第一次创建片段时,savedInstanceState的值为null,但对于后续的重新创建,即使不重写onSaveInstanceState(),该值也始终为非null。

11.只有当片段提供有效的视图实例时,才会创建片段的视图生命周期。在大多数情况下,您可以使用带有@LayoutId的片段构造函数,它会在适当的时间自动膨胀视图。您还可以重写onCreateView()以编程方式膨胀或创建片段的视图。

如果且仅当片段的视图是用非null视图实例化的,则该视图将在片段上设置,并且可以使用getView()检索该视图。然后使用与片段视图相对应的新初始化LifecycleOwnerLiveData()更新getViewLifecycleOwnerLiveData()。此时还将调用onViewCreated()生命周期回调。

这是设置视图初始状态、开始观察其回调更新片段视图的LiveData实例以及在片段视图中的任何RecyclerView或ViewPager2实例上设置适配器的适当位置。

  相关解决方案