在这种布局我们可以不再使用wrap_content、match_parent等方式来制定控件的大小,而是直接运行控件在布局中所占的百分比,这样的话就可以轻松实现平方布局甚至是任意比例分割布局的效果了。
由于LinearLayout本身已经支持按比例指定控件的大小,因此百分百布局只是为FragLayout和RelativeLayout进行了功能扩展,提供了PercentFrameLayout和PercentRelativeLayout这两个全新的布局。
使用该布局的时候需要加上支持库。方法为:
1.在app/build.gradle文件,在dependencies闭包中添加下面内容:其中的25.3.1为自己的gradle支持的版本
dependencies { compile 'com.android.support:percent:25.3.1' }
修改了之后,点击android studio上方的Sync Now即可自动下载该类库。
<?xml version="1.0" encoding="utf-8"?> <android.support.percent.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" android:orientation="vertical"> <Button android:id="@+id/button1" android:text="Button1" android:layout_gravity="left|top" app:layout_widthPercent="50%" app:layout_heightPercent="50%"/> <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="bottom|left" 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%"/> </android.support.constraint.ConstraintLayout>
显示如下:
由于PercentFrameLayout会继承Fragment的所有属性,所以子布局默认放在左上角,所以需要加上layout_gravity来让其放在左上、右上、左下、右下。