1. 程式人生 > >RelativeLayout的layout_marginBottom屬性失效問題

RelativeLayout的layout_marginBottom屬性失效問題

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

    <TextView
        android:id="@+id/text_view1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="50dp"
        android:text="hello world1" />
</RelativeLayout>

讀完這個佈局,通過腦補畫面,你可能認為:一個TextView距底部50dp畫素。

如果你真的這樣認為,那麼你就錯了,上面的佈局執行後的真實情況如圖:


對,android:layout_marginBottom="50dp"這句程式碼失效了,為什麼呢?我也不知道,繼續尋找規律

接下來把RelativeLayout設定layout_height=“match_parent”,

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="<span style="color:#ff0000;">match_parent</span>">

    <TextView
        android:id="@+id/text_view1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="50dp"
        android:text="hello world1" />
</RelativeLayout>
看效果:


這時發現android:layout_marginBottom="50dp"這句程式碼起作用了。

然後再繼續研究,RelativeLayout android:layout_height="wrap_content"的情況,在text_view1上面再增加一個TextView

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="<span style="color:#ff0000;">wrap_content</span>">

    <TextView
        android:id="@+id/text_view2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/text_view1"
        android:layout_marginBottom="50dp"
        android:text="hello world2" />

    <TextView
        android:id="@+id/text_view1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_marginBottom="10dp"
        android:text="hello world1" />
</RelativeLayout>
執行效果:

這時發現新增加的TextView的android:layout_marginBottom="50dp"起作用了。

最後總結:
RelativeLayout佈局裡

1、當設定為android:layout_height="wrap_content"時,最下面的控制元件layout_marginBottom屬性無效,如果其他控制元件使用layout_above讓自己處於最下面的控制元件之上,那麼layout_marginBottom屬性有效

2、當設定為android:layout_height="match_parent"時,或者高度為固定值,那麼最下面的控制元件layout_marginBottom屬性才會有效