Android开发中布局与组件(二)—— padding 与 margin 的区别

在 Android开发中我们会设置某个视图相对于别的视图的距离,这时我们就要用到 marginpadding ,但是有时候很容易把这两个属性弄混淆,那我们就看看他们的区别。

  • 外边距(margin): 属于布局参数,决定两个组件之间的距离。作用于多个组件之间。
  • 内边距(padding):不属于布局参数,这个参数是为了告诉组件在绘制自己的时候应该比自己的内容(content)大多少。作用于组件自己。

具体情况如下:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="#ffffca">

    <TextView
        android:id="@+id/text1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="8dp"
        android:text="text1"
        android:textSize="30sp"
        android:background="#ff0000"/>

    <TextView
        android:id="@+id/text2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/text1"
        android:layout_margin="8dp"
        android:padding="8dp"
        android:text="text2"
        android:textSize="30sp"
        android:background="#0000ff"/>

</RelativeLayout>

效果图如下:

在我们代码中定义的两个 TextView 中唯一的区别是 text2text1 多了一个 android:padding="8dp" 属性,从而使他们的表现出来的样子大不相同,在 text2text1 中同时定义的 android:layout_margin="8dp" 属性是让父视图在布置他们的位置是注意保持他们周围的边距为 8dp ,即 text1 距屏幕顶部的距离是 8dp ,距屏幕左边也是 8dp , text2 也是同样的,所以就导致 text1 底部和 text2 顶部的距离就是 16dp
text2 由于有 android:padding="8dp" 的属性,所以就导致他的实际大小要比 text1 要大,如果我们把 text1 放在 text2 上边,就会发现 text1 的上下左右四个边 距 text2 的四个边的距离都是 8dp ,这就是 padding 属性的作用,它使得组件在保证内容不变的情况下增加组件的大小。

希望可以帮到你~

PS:开发了一个制作个性二维码的应用,有兴趣的朋友可以试一试~ 创意二维码制作

猜你喜欢

转载自blog.csdn.net/ToBeTheOnlyOne/article/details/79321698
今日推荐