Android到Androidx記錄

本文轉載自“翻譯不了的聲響”寫的《Android AndroidX的遷移》,地址在文末

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)更新升級插件

  • 將AS更新至 AS 3.2及以上;
  • Gradle 插件版本改爲 4.6及以上;
    項目下 gradle/wrapper/gradle-wrapper.propertie 文件中的distributionUrl改爲:

 

distributionUrl=https\://services.gradle.org/distributions/gradle-4.6-all.zip
  • compileSdkVersion 版本升級到 28及以上;
  • buildToolsVersion 版本改爲 28.0.2及以上。

插件更新提示

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)修改支持庫類
 將原來importandroid.**包刪除,重新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步手動去修改遷移)

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遷移問題

《Android Support庫和AndroidX衝突問題》

4. AndroidX影響

  雖然說目前對我們沒有多大影響,我們可以不使用仍然使用舊版本的支持庫,畢竟沒有強制,但長遠來看還是有好處的。AndroidX重新設計了包結構,旨在鼓勵庫的小型化,支持庫和架構組件包的名字也都簡化了;而且也是減輕Android生態系統碎片化的有效方式。


作者:翻譯不了的聲響
鏈接:https://www.jianshu.com/p/7dc111353328

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章