《第一行代码》百分比布局 :error: attribute layout_heightPercent (XXX)not found

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

原文地址:https://www.cnblogs.com/hbuwyg/p/11173649.html