【Android】Fragment将废弃onActivityCreated

Android的Fragment即将迎来新版本1.3.0的发布。通过近期的几个alpha版本,我们可以了解到其中带来的一些重要更新:

支持Activity Result APIs

Added support for the ActivityResultRegistry API to handle the startActivityForResult() + onActivityResult()

配合Activity Result APIs的需求,增加了对ActivityResultRegistry API的支持。Activity Result APIs是取代startActivityForResult + onActivityResult 新的处理方式,需要在 Activity 和 Fragment 中分别得到支持才能work

参考 深入理解ActivityResultContract


带参数@LayoutRes的构造函数

Fragment now contain a second constructor that takes a @LayoutRes int that indicates the layout which onCreateView() should inflate by default

Framgent增加了一个构造函数,接受一个@LayoutRes int参数,用来指定默认的layout文件,可以省略onCreateView的重写

class HomeFragment: Fragment(R.layout.frag_home) {
  // ...
}

废弃onActivityCreated

The onActivityCreated() method is now deprecated. Code touching the fragment’s view should be done in onViewCreated() (which is called immediately before onActivityCreated()) and other initialization code should be in onCreate().

这次更新中最值得开发者注意的一个内容是fragment的onActivityCreated将被废弃,这有利于降低Lifecycle复杂度。那应该如何获取Activity的onCreated通知呢?官方给了如下建议:

To receive a callback specifically when the activity’s onCreate() is complete, a LifeCycleObserver should be registered on the activity’s Lifecycle in onAttach(), and removed once the onCreate() callback is received.

可以在onAttach的时候,通过订阅Activity的lifecycle来获取Activity的onCreate事件,但是不要忘了remove,可以在onDetach的时候或者在onCrate之后立即remove


支持ViewTreeLifecycleOwner

Added support for the ViewTreeLifecycleOwner.get(View) API that it will return the Fragment’s viewLifecycleOwner as the LifecycleOwner for any Views returned by onCreateView().

此功能主要是为了配合实现 Lifecycle 2.3.0中增加的ViewTreeLifecycleOwner.get(View) 扩展方法,这是个非常实用的方法,可以基于View获取一个最近的LifecycleOwner。在Fragment中,可以针对onCreateView返回的View,获取该Fragment的ViewLifecycleOwner

参考:使用ViewTreeLifecycleOwner获取Lifecycle


废弃setRetainInstance

The setRetainInstance() method on Fragments has been deprecated. With ViewModel, developers have a specific API for retaining state that can be associated with Activities, Fragments, and Navigation graphs.

retainInstance属性默认值为false。当设置为true,因屏幕旋转等引起的Activity重建时,fragment不会随之销毁。所以我们常用Fragment来保存一些不希望因Activity重建而销毁的数据。现在此需求可以使用ViewModel替代,所以此属性可以废弃


拥抱ViewPager2

With the release of ViewPager2 1.0.0, the FragmentPagerAdapter and FragmentStatePagerAdapter classes for interacting with ViewPager have been deprecated.

随着ViewPager2 1.0.0的发布,ViewPager中使用的 FragmentPagerAdapterFragmentStatePagerAdapter 将被废弃。今后同类需求的实现将转为使用ViewPager2的同名Adapter。


参考


深入理解ActivityResultContract
使用ViewTreeLifecycleOwner获取Lifecycle

你可能感兴趣的:(Android)