Android布局易混肴属性

前言

在Android UI开发中经常使用android:layout_gravity和android:gravity;padding以及margin属性。平常使用中不是很清楚具体的作用,故此记录一下这些小问题。

1.android:layout_gravity与android:gravity的区别

  1. android:layout_gravity
    代表子元素在父容器中的对齐方式,例如:给Button设置right,它将位于整个父容器的右侧。
  2. android:gravity
    代表子元素内部的对齐方式,例如:给Button设置text,再设置gravity属性为center,文字内容将居中显示在Button中。

案例:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:layout_gravity="center_horizontal"
        android:textSize="30sp"
        android:text="Hello World!" />

</LinearLayout>

在这里插入图片描述

  • 给Button设置android:gravity = “center” 需要配和android:layout_width="match_parent"使用,否则无效。
  • 在父布局竖直排列时,android:layout_gravity = "center_vertical"无法生效;反之一样

2.padding与margin的区别

  1. padding
    指距元素内部边框的距离。
  2. margin
    指该元素与相对元素之间的距离。

猜你喜欢

转载自blog.csdn.net/qq_34341338/article/details/83538302