关于LinearLayout下layout_margin属性的深入探讨

这里的探讨全部在LinearLayout下的,其他布局暂时没有研究。

        一直对于layout_margin的用法比较困惑,感觉比较玄学。故仔细研究了一番,特此笔记。

先看下layout_margin这个属性吧

<LinearLayout
    android:orientation="horizontal"
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="50dp"
        android:text="ok" />
</LinearLayout>

效果图:

从效果图上可以看到,margin=50dp并不是与上下左右都距离50dp,

而是在上下方向上距离上边界50dp

在左右方向上距离左边界50dp

那么为什么会这样呢,

因为默认的上下方向对齐方式是向上对齐

       默认的左右方向对齐方式是向左对齐

那么我们修改对齐方式看看会怎么样吧?

<LinearLayout
    android:orientation="horizontal"
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right|bottom"
        android:layout_margin="50dp"
        android:text="ok" />
</LinearLayout>

效果图:

em....确实是可以向底对齐了现在距离底的距离是50dp了但是还是左对齐怎么回事呢?

我们LinearLayout的对齐方式是水平哦,这时候默认的话LinearLayout下所有的控件都是水平排列,并且向左对齐的。

我们这里只是更改了一个控件的对齐方式,可能不太行哦。

我们更改LinearLayout的gravity试试看

<LinearLayout
    android:orientation="horizontal"
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="right|bottom"
   >
    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="50dp"
        android:text="ok" />

</LinearLayout>

 效果:

这样子就行了啊。

我们思考vertical的话,就是默认垂直排列,并且向左对齐,如果想更改 操作类似。

我们这种思考引入layout_marginLeft中去

看一个例子:

<LinearLayout
    android:orientation="horizontal"
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent"
   >

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="20dp"
        android:text="ok" />

</LinearLayout>

效果:

一点效果都没有是不是?

按照刚才通过实验得出想法我们设置一下LinearLayout的orientation

<LinearLayout
    android:orientation="horizontal"
    xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="right"
   >

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginRight="20dp"
        android:text="ok" />

</LinearLayout>

效果:

哈哈是不是可以了。

注意:在LinearLayout下marginRight是距离右边的最近View的距离哦,其他margin类似!

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章