在《第一行代码》中,原先按照书中内容配置,无法正常运行,记录一下解决过程。
书中步骤如下:
- 在/app/build.gradle中添加依赖
compile 'com.android.support:percent:24.2.1'
在添加上述依赖后会有警告使用androidx,先忽略它
- 之后在activity_main.xml中进行布局
<android.support.percent.PercenFrameLayout>
......
......
</android.support.percent.PercenFrameLayout>
主要到在输入中编辑器不会像写其他布局时候一样自动填充。
- 运行程序,发现模拟器上android程序卡死。
解决过程:
在网上搜索了解决方法,大多都是修改版本,我运行起来依然无效。在查阅文档资料后(支持库工键映射),发现 com.android.support:percent
很久以前就迁移到了 androidx.percentlayout:percentlayout
。于是我就在依赖中加入androidx.percentlayout:percentlayout
库代替之前的那个库。在重新引入PercentFrameLayout
布局,之后成功了。猜测可能是最新版本的android studio不支持原先的库了????
解决步骤
- 引入依赖。(修改app/build.gradle)
implementation 'androidx.percentlayout:percentlayout:1.0.0'
修改后会弹出下图,点击 sync now
也可以通过"点点点"来添加和修改依赖库版本。如下图
- 在activity_main.xml 中修改布局为(此时在输入的过程中便可以自动代码补全。
<androidx.percentlayout.widget.PercentFrameLayout>
......
......
</androidx.percentlayout.widget.PercentFrameLayout>
完整代码如下:(activity_main.xml)
<?xml version="1.0" encoding="utf-8"?>
<androidx.percentlayout.widget.PercentFrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/btn1"
android:layout_gravity="left|top"
android:text="btn1"
android:textAllCaps="false"
app:layout_heightPercent="50%"
app:layout_widthPercent="50%" />
<Button
android:id="@+id/btn2"
android:layout_gravity="right|top"
android:text="btn2"
android:textAllCaps="false"
app:layout_heightPercent="50%"
app:layout_widthPercent="50%" />
<Button
android:id="@+id/btn3"
android:layout_gravity="left|bottom"
android:text="btn3"
android:textAllCaps="false"
app:layout_heightPercent="50%"
app:layout_widthPercent="50%" />
<Button
android:id="@+id/btn4"
android:text="btn4"
android:layout_gravity="right|bottom"
app:layout_widthPercent="50%"
app:layout_heightPercent="50%"/>
</androidx.percentlayout.widget.PercentFrameLayout>
- 运行一下,成功了!