Android Studio 3.4.2 | gradle 5.1.1
發現問題:
學習《第一行代碼》百分比布局,很多人遇到了:error: attribute layout_heightPercent (XXX)not found
網上搜索,大多是推薦增加或修改:
compile 'com.android.support:percent:XXX’
implementation 'com.android.support:percent:XXX’
按照帖子各種修改,最終還是不能正常執行。
分析問題:
經仔細研究,在Android studio 3.2+中,默認布局已經不是原來的 Android布局,已經變為AndroidX !
如果仍舊想用Android布局,參考:低版本如何不使用AndroidX編譯;AndroidX 概覽。
大勢所趨,建議還是學着用AndroidX吧……
按照AndroidX標准,以前的方法都不好使了~
官方說明:遷移到 AndroidX
在這個網頁搜索percent,得到:
解決方案:
第一步:修改build.gradle的dependencies
用AndroidX,需要增加這樣一行:implementation 'androidx.percentlayout:percentlayout:1.0.0'
第二步:activity_main.xml文件
幫助文檔:PercentFrameLayout
欲達到與郭神書籍相同效果,AndroidX代碼如下:
1 <?xml version="1.0" encoding="utf-8"?> 2 <androidx.percentlayout.widget.PercentFrameLayout 3 xmlns:android="http://schemas.android.com/apk/res/android" 4 xmlns:app="http://schemas.android.com/apk/res-auto" 5 android:layout_width="match_parent" 6 android:layout_height="match_parent"> 7 8 <Button 9 android:id="@+id/button1" 10 android:layout_gravity="left|top" 11 android:text="河" 12 android:layout_width="match_parent" 13 android:layout_height="match_parent" 14 app:layout_heightPercent="50%" 15 app:layout_widthPercent="50%" /> 16 17 <Button 18 android:id="@+id/button2" 19 android:layout_gravity="right|top" 20 android:text="北" 21 android:layout_width="match_parent" 22 android:layout_height="match_parent" 23 app:layout_heightPercent="50%" 24 app:layout_widthPercent="50%" /> 25 26 <Button 27 android:id="@+id/button3" 28 android:layout_gravity="left|bottom" 29 android:text="大" 30 android:layout_width="match_parent" 31 android:layout_height="match_parent" 32 app:layout_heightPercent="50%" 33 app:layout_widthPercent="50%" /> 34 35 <Button 36 android:id="@+id/button4" 37 android:layout_gravity="right|bottom" 38 android:text="學" 39 android:layout_width="match_parent" 40 android:layout_height="match_parent" 41 app:layout_heightPercent="50%" 42 app:layout_widthPercent="50%" /> 43 44 </androidx.percentlayout.widget.PercentFrameLayout>
效果圖:
SourceCode:https://github.com/HBU/AndroidTest/tree/master/Layout/Percent