AndroidX了解一下

17,328 阅读2分钟

1.说明

官方原文如下

We hope the division between android.* and androidx.* makes it more obvious which APIs are bundled with the platform, and which are static libraries for app developers that work across different versions of Android.

简单地说就是新的库可以在不同的Android版本上使用。比如之前我们如果使用support为27.1.1的相关依赖库时。可能需要所有相关的support 库都为27.1.1。如果其中有bug的话,可能需要所有的都去升级,存在一个绑定关系,而且正式版的发布周期也很长。

通过AndroidX,我们可以看到实时实现的特性和bug修复。升级个别依赖,不需要对使用的所有其他库进行更新。这就和我们使用Github上的开源库一样的,出了问题,我们可以提出bug和意见。作者修复后,发布新版本,我们就可以直接替换使用了。更加的透明便捷。

2.变化

我选取了几个常用依赖库,我们可以看看变化:

Old build artifact AndroidX build artifact
com.android.support:support-compat androidx.core:core:1.0.0+
com.android.support:appcompat-v7 androidx.appcompat:appcompat:1.0.0+
com.android.support:design com.google.android.material:material:1.0.0+
com.android.support:multidex androidx.multidex:multidex:2.0.0+
com.android.support:recyclerview-v7 androidx.legacy:legacy-support-v4:1.0.0+
com.android.support:viewpager androidx.viewpager:viewpager:1.0.0+
com.android.support:support-fragment androidx.fragment:fragment:1.0.0+

当然涉及的不止这些库,更详细的变化内容可以查看官方文档

我们可以添加appcompat依赖对比一下:

implementation 'com.android.support:appcompat-v7:28.0.0-beta1'
或
implementation 'androidx.appcompat:appcompat:1.0.0-beta01'

可以看到详细变化

  

同时我们看到viewpagerswiperefreshlayoutcoordinatorlayout 等一些UI组件被分离了出来,这样也是便于更好的使用,职责分明,以减轻不使用ProGuardMultidex的应用程序和测试的压力。

3.影响

官方博客中有说道,为了给开发者一定迁移的时间,所以28.0.0的稳定版本还是采用android.support。但是所有后续的功能版本都将采用androidx

其实对于我们影响也不是很大,我们可以选择不使用,毕竟不是强制的。但长远看来还是有好处的。接受变化,拥抱变化也是我们程序猿需要有的精神,欢迎尝试。

对于有写一些开源项目的人,可能会有一些影响。比如你有一个关于RecyclerView的拓展库,那么你就需要去让他支持AndroidX,否则你懂的。

我有去看了一下我们常用的butterknifeglide 等都已经适配了AndroidX,不得不说真是很良心。

这里写图片描述

这里写图片描述

4.迁移

如果一个一个去替换当然很麻烦了,所以在Android Studio 3.2 Canary中添加了一键迁移的功能Refactor -> Migrate to AndroidX

首先你的gradle版本至少为3.2.0以上,以及compileSdkVersion为28以上。

classpath 'com.android.tools.build:gradle:3.2.0+'

如果你是一个新项目,如果使用AndroidX相关依赖,需要在gradle.properties文件里添加配置:

android.useAndroidX=true
android.enableJetifier=true

如果你想使用AndroidX,但是之前的不迁移,可以这样配置:

android.useAndroidX=true
android.enableJetifier=false

5.参考

当然迁移最好是出了正式版后在尝试。这里目的也就和标题一样,了解一下(坚决不做标题党哈)。