了解AndroidX
谷歌的文檔工作做得比國(guó)內(nèi)任何一家互聯(lián)網(wǎng)公司都要好贸人,直接參考安卓開發(fā)者網(wǎng)站:AndroidX Overview
遷移到AndroidX
-
保存當(dāng)前工作空間狀態(tài)副签,萬一遷移出錯(cuò)可以恢復(fù)當(dāng)前狀態(tài)。當(dāng)然Android Studio已經(jīng)想到了這一點(diǎn)阶牍,在開始遷移(migrate)之前可以選擇幫你打一個(gè)zip包進(jìn)行另存(Backup project as Zip file)笙纤。
Backup project as Zip file 如果當(dāng)前Android Studio是3.2及以上版本啄骇,直接點(diǎn)菜單欄Refactor > Migrate to AndroidX
報(bào)錯(cuò)及修改:
- You need to have at least have compileSdk 28 set in your module build.gradle to migrate to AndroidX.
之前創(chuàng)建的老項(xiàng)目依賴版本一般都不會(huì)到28宵蛀,故需要修改到最新的28昆著,新創(chuàng)建的項(xiàng)目也得注意依賴版本得是28以上才行。
修改: 主Module的 build.gradle 中
compileSdkVersion 28
- The gradle plugin version in your project build.gradle file needs to be set to at least com.android.tools.build:gradle:3.2.0 in order to migrate to AndroidX.
同理保證gradle插件是最新版本术陶。
修改project 的 build.gradle :
classpath 'com.android.tools.build:gradle:3.2.0'
報(bào)錯(cuò)如下:
Minimum supported Gradle version is 4.6. Current version is 4.4.
修改 gradle-wrapper.properties 中:
distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zip
到這里常規(guī)遷移工作已經(jīng)全部完成了凑懂。
- 找不到android.support.annotation.CallSuper; android.support.annotation.UiThread
以上提醒事項(xiàng)都完成之后編譯還是出錯(cuò)了。發(fā)現(xiàn)在build目錄自動(dòng)生成的所有XXXactivity_ViewBinding都報(bào)找不到注解 @UiThread @CallSuper梧宫,看這個(gè)自動(dòng)生成類的名字大概就可以猜到是ButterKnife出問題了
想到之前看到過JakeWharton早就為ButterKnife兼容了androidX,
找到ButterKnife的倉(cāng)庫(kù)看到已經(jīng)升級(jí)到9.0.0-rc1了接谨,升級(jí)至9.0.0-rc1后再次編譯一次摆碉。
- 此時(shí)已經(jīng)可以運(yùn)行了,但是build還是會(huì)報(bào)錯(cuò)
ERROR: [TAG] Failed to resolve variable '${animal.sniffer.version}'
ERROR: [TAG] Failed to resolve variable '${junit.version}'
上網(wǎng)一查:stackoverflow
直接File->Invalidate Caches / restart,不再報(bào)錯(cuò)了脓豪。
- 如果是老項(xiàng)目中引入了第三方框架巷帝,自動(dòng)遷移過程中在gradle.properties已經(jīng)自動(dòng)為我們添加了兩個(gè)配置,如果是手動(dòng)遷移需要自己添加:
With Android Studio 3.2 and higher, you can quickly migrate an existing project to use AndroidX by selecting Refactor > Migrate to AndroidX from the menu bar.
If you have any Maven dependencies that have not been migrated to the AndroidX namespace, the Android Studio build system also migrates those dependencies for you when you set the following two flags to true in your gradle.properties file:
android.useAndroidX=true
android.enableJetifier=true
To migrate an existing project that does not use any third-party libraries with dependencies that need converting, you can set the android.useAndroidX flag to true and the android.enableJetifier flag to false.
修正優(yōu)化gradle中的版本
如果你的工程中將version都集中到了versions.gradle文件中或其他地方跑揉,android studio的自動(dòng)遷移功能只會(huì)修改build.gradle文件中的相應(yīng)版本锅睛,所以需要自己再次整理gradle文件埠巨。
- 參考官網(wǎng)的映射表:androidx-class-mapping
可以直接下載:androidx-class-mapping - 一些特殊的名稱變化
com.android.support:design com.google.android.material:material:1.0.0-rc01