Android之PercentFrameLayout(百分比布局)

一、在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);
    }
}

四、运行效果

  • 5
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值