2014-11-04 113 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>