android.support遷移到androidx

前言

Google 2018 IO 大會推出了 Android新的擴展庫 AndroidX,用於替換原來的 Android擴展庫,將原來的android.替換成androidx.;只有包名和Maven工件名受到影響,原來的類名,方法名和字段名不會更改。官方早就推薦將support庫遷移到androidx,因爲後續support庫不會再做更新。
遷移時只需要3.2版本及以上的android studio,在菜單refactor中點擊migrate to androidx即可,該向導會提示需要做的更新。其中包括gradle版本至少3.2以上,compileSdkVersion 版本28以上。
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

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

瞭解androidX可以看這一篇:androidX瞭解一下
更多androidX詳細內容看:官方文檔

關於gradle低版本升級可以看這篇文章:https://blog.csdn.net/u013183608/article/details/89428563

替換成androidx後遇到的問題

1、對findViewById的引用不明確

描述:Activity 中的方法 findViewById(int) 和 AppCompatActivity 中的方法 findViewById(int) 都匹配其中, T是類型變量:T擴展已在方法 findViewById(int)中聲明的View

解決方法:compileSdkVersion不一致,應該進行統一

2、v4jar包keyeventcompat不存在

描述:錯誤: 找不到符號
符號: 類 KeyEventCompat
位置: 程序包 androidx.core.view

原因:KeyEventCompat類被取消了hasNoModifiers方法,而該方法已經被KeyEvent實現了
原代碼:

		if (KeyEventCompat.hasNoModifiers(event)) {
		     handled = arrowScroll(FOCUS_FORWARD);
		} else if (KeyEventCompat.hasModifiers(event, KeyEvent.META_SHIFT_ON)) {
		     handled = arrowScroll(FOCUS_BACKWARD);
		}

修改後代碼

		if (event.hasNoModifiers()) {
		    handled = arrowScroll(FOCUS_FORWARD);
		} else if (event.hasModifiers(KeyEvent.META_SHIFT_ON)) {
		    handled = arrowScroll(FOCUS_BACKWARD);
		}

3、ERROR: [TAG] Failed to resolve variable ‘${junit.version}’

解決方法:file->Invalidate Caches / restart

4、Error:error: resource previously defined here.

原因:自定義View時自定義屬性使用了系統的屬性名稱
解決方案:
1、重命名自已定義的屬性,以避免與系統的屬性名稱重複

        <declare-styleable name="TestTextView">
                <attr name="text_color" format="color"/>
                <attr name="text_size" format="float" />
        </declare-styleable>

2、不對textColor進行重命名,直接引用系統的textColor,然後在xml裏面使用 時,就不能使用自定義的命名空間了(例如:app:),得用使用原生的引用(android:)

	    <declare-styleable name="TestTextView">
	            <attr name="textColor"/>
	            <attr name="textSize"/>
	    </declare-styleable>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章