首页

源码搜藏网

首页 > 安卓源码 > 技术博客 >

Android AndroidX的迁移

创建时间:2019-04-08 17:29  浏览

Google 2018 IO 大会推出了 Android新的扩展库 AndroidX,用于替换原来的 Android扩展库,将原来的android.*替换成androidx.*;只有包名和Maven工件名受到影响,原来的类名,方法名和字段名不会更改。接下来我们来看看使用 AndroidX的扩展库需要哪些配置。

1. AndroidX变化

1)常用依赖库对比:

Old build artifact AndroidX build artifact
com.android.support:appcompat-v7:28.0.2 androidx.appcompat:appcompat:1.0.0
com.android.support:design:28.0.2 com.google.android.material:material:1.0.0
com.android.support:support-v4:28.0.2 androidx.legacy:legacy-support-v4:1.0.0
com.android.support:recyclerview-v7:28.0.2 androidx.recyclerview:recyclerview:1.0.0
com.android.support.constraint:constraint-layout:1.1.2 androidx.constraintlayout:constraintlayout:1.1.2

?更多详细变化内容,可以下载CSV格式映射文件;
2)常用支持库类对比:

Support Library class AndroidX class
android.support.v4.app.Fragment androidx.fragment.app.Fragment
android.support.v4.app.FragmentActivity androidx.fragment.app.FragmentActivity
android.support.v7.app.AppCompatActivity androidx.appcompat.app.AppCompatActivity
android.support.v7.app.ActionBar androidx.appcompat.app.ActionBar
android.support.v7.widget.RecyclerView androidx.recyclerview.widget.RecyclerView

?更多详细变化内容,可以下载CSV格式映射文件。

2. AndroidX配置

1)更新升级插件

distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zip

Android AndroidX的迁移

2)开启迁移AndroidX
?在项目的gradle.properties文件里添加如下配置:

android.useAndroidX=true
android.enableJetifier=true

?表示项目启用 AndroidX 并迁移到 AndroidX。

3)替换依赖库
?修改项目app目录下的build.gradle依赖库:

implementation 'com.android.support:appcompat-v7:28.0.2' → implementation 'androidx.appcompat:appcompat:1.0.0'
implementation 'com.android.support:design:28.0.2'  → implementation 'com.google.android.material:material:1.0.0'
implementation 'com.android.support.constraint:constraint-layout:1.1.2' → implementation 'androidx.constraintlayout:constraintlayout:1.1.2'
...

4)修改支持库类
?将原来import的android.**包删除,重新import新的androidx.**包;

import android.support.v7.app.AppCompatActivity; → import androidx.appcompat.app.AppCompatActivity;

5)一键迁移AndroidX库
?AS 3.2 及以上版本提供了更加方便快捷的方法一键迁移到 AndroidX。选择菜单上的ReFactor —— Migrate to AndroidX... 即可。(如果迁移失败,就需要重复上面1,2,3,4步手动去修改迁移)

Android AndroidX的迁移

注意:如果你的项目compileSdkVersion 低于28,点击Refactor to AndroidX...会提示:

You need to have at least have compileSdk 28 set in your module build.gradle to refactor to androidx

提示让你使用不低于28的sdk,升级最新到SDK,然后点击 Migrate to AndroidX...,AS就会自动将项目重构并使用AndroidX库。

3. AndroidX影响

??虽然说目前对我们没有多大影响,我们可以不使用仍然使用旧版本的支持库,毕竟没有强制,但长远来看还是有好处的。AndroidX重新设计了包结构,旨在鼓励库的小型化,支持库和架构组件包的名字也都简化了;而且也是减轻Android生态系统碎片化的有效方式。

4. AndroidX迁移问题

上一篇:Android开发浅谈移动端 View 的显示过程
下一篇:Android Q Beta 2 已上线!我们来看看都做了哪些更新

相关内容

热门推荐