Android P 中弃用的片段

Fragments deprecated in Android P

我正在查看 documentation 并找到了这个

This class was deprecated in API level P.

为什么在 android P 中弃用片段?

支持库片段将保留。 Google 鼓励您使用支持库版本在所有 API 级别上获得一致的行为、向后移植的错误修复以及生命周期和 ViewModel 支持。

Old Reference Link(Dead)

New Reference Link

支持库 27.1.0 中的重写

Ian's medium post(2018 年 2 月 28 日)给了我们一个解释。他是 Google 的 Android 框架开发人员。

Loaders in Support Library 27.1.0

For Support Library 27.1.0, I rewrote the internals of LoaderManager, the class powering the Loaders API and I wanted to explain the reasoning behind the changes and what to expect going forward.

Loaders and Fragments, a history
From the beginning, Loaders and Fragments were pretty tightly tied together at the hip. This meant that a lot of the code in FragmentActivity and Fragment were there to support Loaders, despite the fact that there are indeed fairly independent. …

What’s changed in 27.1.0
With 27.1.0, the technical debt of Loaders has been greatly reduced: …

Note: Obviously, these changes only apply to Support Library Loaders. If you are using Android framework Loaders, please switch to the Support Library Loaders as soon as possible. There are no bug fixes or improvements planned for the framework Loader APIs.

FragmentFragmentActivity 中的代码似乎已被重构以使 Loaders 成为可选依赖项。

根据 the release note,新的实现基于 Lifecycle

Important Changes
The underlying implementation of Loaders has been rewritten to use Lifecycle.

架构组件

Support Library 26.1.0FragmentFragmentActivity中采用了Lifecycle

This is a special release to integrate the Support Library with Lifecycles from Architecture Components. If you are not using the Lifecycles library, you don’t need to update from 26.0.2. For more information, see the Architecture Components release notes.

Important changes

  • Fragment and FragmentActivity (the base class for AppCompatActivity) now implement the LifecycleOwner interface from Architecture Components.

相比之下,AndroidP中的Fragment and Activity还没有实现接口LifecycleOwner

the Google+ post (mentioned in ), Ian发表了评论:

you can't change framework code after it has shipped - it is literally frozen in time. That means no new features and more importantly no bug fixes. That's not a good developer experience, particularly when we do have a fully supported, up to date, backward compatible version in the Support Library.

我想这就是AndroidP不采用Lifecycle的原因。因此 Fragment 在 Android P.

中被弃用

如果有人正在寻找通过 class 名称实例化片段的方法。

旧方法:

Fragment.instantiate(context, fragmentClass)

新方式:

val fm: FragmentManager = ...
fm.fragmentFactory.instantiate(ClassLoader.getSystemClassLoader(), fragmentClass)

使用扩展:


文件名:FragmentManagerExt.kt

import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager

fun FragmentManager.instantiate(className: String): Fragment {
    return fragmentFactory.instantiate(ClassLoader.getSystemClassLoader(), className)
}

用法示例:

val fragment = supportFragmentManager.instantiate(fragmentClassName)

Android x 中使用 supportFragmentManager 代替 fragmentManager。 =10=]