迁移android支持库到androidx

什么是android支持库

打开你的Andriod Studio,工程中app模块的build.gradle拖到底,看到类似这些内容:

dependencies {
    implementation fileTree(include: ['*.jar'], dir: 'libs')
    implementation 'com.android.support:appcompat-v7:27.1.1'
    implementation 'com.android.support.constraint:constraint-layout:1.1.3'
    implementation 'com.android.support:recyclerview-v7:27.1.1'
    implementation 'com.android.support:exifinterface:27.1.1'
    implementation 'com.android.support:support-v4:27.1.1'
}

里面带有com.android.support字样的,就是android支持库(support library)了。

拿最常见的appcompat来说,有-v4和-v7这样的“版本”信息在,但是又不是SDK version开头的版本,很晕,对吧?

v4和v7都是为了兼容性考虑的,从android sdk 28开始,又出现了androidx;如果新建的是andriod sdk 29的工程:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 29
    ...
}

那么,还必须把android支持库都迁移到androidx。

什么时候需要迁移android支持库到androidx

现在(2020年1月15日)新建的AS工程,默认用的compileSdkVersion 29,这要求必须用androidx而不是android.support:gradle直接报编译错误。

我不想降级compileSdkVersion到27,虽然我知道这很可能是可以解决问题的。为什么不肯将就一下?因为androidx其实就是为了解决android支持库的v4和v7等一系列头疼的版本号的问题的。用androidx,代表未来。持续用过时的技术,尤其是google加持的技术,没有什么好下场的。

怎么从android支持库迁移到androidx

我们不需要手动修改app的build.gradle中每一个dependencies,Android Studio还没有那么傻缺。

步骤1:
gradle.properties中添加:

android.useAndroidX=true
android.enableJetifier=true

步骤2:
Android Studio菜单栏->Refactor->Migrate to AndroidX

会提示确认是否refactor(重构),选择do refactor,过一会儿就好了。

refs

Androidx初尝及其新旧包对照表

猜你喜欢

转载自www.cnblogs.com/zjutzz/p/12197670.html