2014-11-04 92 views
0

我已經看到,一個元素的寬度可以設置爲屏幕寬度的一小部分通過使用相對佈局(代碼下面僅示出相關的屬性):在佈局元素相對高度

<LinearLayout> 
    <ImageView 
    android:layout_width="0dp" 
    android:layout_weight=".40" /> 
    </imageView> 
    <TextView 
    android:layout_width="0dp" 
    android_layout_weight=".60" /> 
</LinearLayout> 

但是......顯然這個技巧不能用於分配元素的比例高度。如果我嘗試設置0dp的layout_height,Eclipse會投訴。如果我想要帶有標題的圖像,圖像佔用屏幕高度的40%,並且下方的標題獲得60%,我該怎麼辦?

回答

0

您的確可以爲LinearLayout的水平和垂直方向分配權重。

水平方向例如:

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

    <ImageView 
     android:layout_width="0dp" 
     android:layout_height="match_parent" 
     android:layout_weight=".40" /> 

    <TextView 
     android:layout_width="0dp" 
     android:layout_height="match_parent" 
     android:layout_weight=".60" /> 

</LinearLayout> 

垂直方位例如:

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

    <ImageView 
     android:layout_width="match_parent" 
     android:layout_height="0dp" 
     android:layout_weight=".40" /> 

    <TextView 
     android:layout_width="match_parent" 
     android:layout_height="0dp" 
     android:layout_weight=".60" /> 

</LinearLayout> 

順便說一句,這是非常有用的知道,你不必指定浮點數的權重。 Android會簡單地總結所有的權重,然後除以總數得到每個的百分比。因此,使用4和6分別爲layout_weights也可以。

+0

啊哈!關鍵是LinearLayout中的屬性android:orientation =「vertical」。謝謝。 – rmhartman 2014-11-05 03:02:45

0

將android:orientation =「vertical」添加到您的佈局,然後將layout_height = 0dp和weight設置爲想要的值。

所以:

<LinearLayout 
    android:orientation="vertical"> 
    <ImageView 
    android:layout_height="0dp" 
    android:layout_weight=".40" /> 
    </imageView> 
    <TextView 
    android:layout_height="0dp" 
    android_layout_weight=".60" /> 
</LinearLayout>