2011-05-24 63 views
4

我有一个LinearLayout有四个视图水平放置。第一个和最后一个组件是一个集合大小。对于内部的两个视图,我想分享可用空间50:50。我将每个设置为“1”的权重,但是当视图放置时,视图根据其内容的不同而不同。 Screen shot of the layout. The data is hidden but it shows how offset the views are不平衡LinearLayout重量分布

这是我的布局xml供参考。

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 
    xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content"> 
    <ImageView 
     android:id="@+id/status" 
     android:src="@drawable/white" 
     android:paddingRight="10dip" 
     android:layout_height="35dip" 
     android:layout_width="35dip"> 
    </ImageView> 
    <TextView android:id="@+id/name" 
     android:text="Name" 
     android:layout_height="fill_parent" 
     android:layout_toRightOf="@id/status" 
     android:layout_width="wrap_content" 
     android:layout_weight="1" 
     android:textSize="25dip"> 
    </TextView> 
    <TextView android:id="@+id/description" 
     android:text="Description" 
     android:layout_toRightOf="@id/name" 
     android:layout_height="fill_parent" 
     android:layout_width="wrap_content" 
     android:layout_weight="1" 
     android:textSize="25dip"> 
    </TextView> 
    <TextView android:id="@+id/time" 
     android:text="Time" 
     android:layout_width="wrap_content" 
     android:layout_height="fill_parent" 
     android:layout_toRightOf="@id/description" 
     android:textSize="25dip"> 
    </TextView> 
</LinearLayout> 

显然这些不是实际的列名,但我为了隐私目的更改了它们。这个布局被ListView使用,它将每个视图的文本改变为它呈现的任何值。名称和说明字段应该对齐,因为它们都是剩余屏幕的50%,但当名称更长时,说明会右移。为什么?

回答

10

对于要考虑的重量,布局尺寸需要是0(零)

<TextView android:id="@+id/name" 
    android:text="Name" 
    android:layout_height="fill_parent" 
    android:layout_width="0dip" 
    android:layout_weight="1" 
    android:textSize="25dip"> 
</TextView> 

我还建议使你的体重加起来是1(和使用分数)或100

因此,对于每个视图,您将使用50或.5。 LinearLayout代码可以在任何权重总和下正常工作,但如果您想稍后使用其他部分修改视图,则难以实现。

此外,如果您没有使用相对布局,请删除toRightOf属性。少即是多。

+0

我刚刚注意到,在阅读谷歌LinearLayout教程。谢谢你,修复它 – Spidy 2011-05-24 22:14:46

+2

从技术上讲,宽度必须全部匹配,而不是零。如果所有宽度都设置为0,200,9000或fill_parent,只要它们匹配,重量将均匀分配。 – Eric 2011-05-24 23:09:57

+0

@Eric - 存在的危险是,您为宽度选择的随机值可能会成为未来的新LayoutParams常量。认为他们永远不会让LayoutParams.MAGIC_LAYOUT = 9000?我不打赌。我想要的是一个LayoutParams.USE_WEIGHT常量。 – slund 2011-05-25 13:38:57

1

尝试使用android:layout_width="fill_parent"代替LinearLayout的所有子项中的“wrap_content”。或者更好的是,在你的XML中制作这样的结构:

<RelativeLayout> 
    <ImageView />  # status, fixed width, alignParentLeft="true" 
    <TextView />  # time, fixed width, alignParentRight="true" 
    <LinearLayout>  # layout_width="fill_parent", toLeftOf="time" toRightOf="status" 
     <TextView /> # name, use layout_weight="1" 
     <TextView /> # description, use layout_weight="1" 
    </LinearLayout> 
</RelativeLayout> 

这应该做你想做的。使用LinearLayout而不是RelativeLayout也可能工作,但您必须稍微尝试一下(我相信使用嵌套布局,就像在我的示例中那样,将完成这项工作)。

+0

我没有尝试这个,但我认为fill_parent也会解决这个问题,因为我之前使用过它。 +1的回复,谢谢 – Spidy 2011-05-24 22:15:19