關於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類似!

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