一、在app/build.gradle的dependencies添加依赖库
implementation 'androidx.percentlayout:percentlayout:1.0.0'
之后需要点击Sync Now,gradle会开始同步,把新添加的百分比布局库引入到项目中
二、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"
>
<!--xmlns:app="http://schemas.android.com/apk/res-auto"
定义了一个app的命名空间,这样才能使用百分比布局的自定义属性-->
<!-- 这个错误提示并不影响程序需的运行,直接忽略 -->
<Button
android:id="@+id/button1"
android:text="Button1"
android:layout_gravity="left|top"
app:layout_widthPercent="50%"
app:layout_heightPercent="50%"
/>
<!-- 这里之所以能使用app前缀就是因为刚刚定义了app的命名空间,和我们
一直能使用android前缀的属性是一个道理-->
<!-- 左上 -->
<Button
android:id="@+id/button2"
android:text="Button2"
android:layout_gravity="right|top"
app:layout_widthPercent="50%"
app:layout_heightPercent="50%"
/>
<!-- 右上 -->
<Button
android:id="@+id/button3"
android:text="Button3"
android:layout_gravity="left|bottom"
app:layout_widthPercent="50%"
app:layout_heightPercent="50%"
/>
<!-- 左下 -->
<Button
android:id="@+id/button4"
android:text="Button4"
android:layout_gravity="right|bottom"
app:layout_widthPercent="50%"
app:layout_heightPercent="50%"
/>
<!-- 右下 -->
<!-- 因为PercentFrameLayout继承了FrameLayout(帧布局)的特性,即
所有控件都会摆放在布局的左上角
为了不让这四个控件重叠,故借助了layout_gravity,
分别摆放在左上、下,右上、下4个位置-->
</androidx.percentlayout.widget.PercentFrameLayout>
三、主方法MainActivity.java
package com.example.percentlayouttest;
import androidx.appcompat.app.AppCompatActivity;
import android.os.Bundle;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
四、运行效果