2012-06-01 43 views
0

在我的android应用程序中,我需要动态地创建几个LinearLayout的文本。 但我无法设定每个元素的权重。我想LL看起来像在xml部分:weightSum xml属性代码android

<LinearLayout 
    android:orientation="horizontal" 
    android:layout_width="fill_parent" 
    android:layout_height="wrap_content" 
    android:layout_margin="10px" 
    android:weightSum="1" 
    android:id="@+id/qwe"> 
<TextView 
    android:layout_weight="0.1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="some" 
/> 
<TextView 
    android:layout_weight="0.8" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="word" 
/> 
<TextView 
    android:layout_weight="0.1" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:text="here" 
    android:gravity="right" 
/> 
</LinearLayout> 

它看起来不错,但我需要动态相同。 在Java代码中我写道:

LinearLayout ll = new LinearLayout(context); 
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT); 
layoutParams.setMargins(10, 10, 10, 10); 
ll.setLayoutParams(layoutParams); 
ll.setOrientation(LinearLayout.HORIZONTAL); 
ll.setBackgroundColor(0xFF888888); 
rootLL.addView(ll); 

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT); 
params.setMargins(10, 10, 10, 10); 

LinearLayout.LayoutParams params1 = params; 
params1.weight = 0.15f; 
TextView one = new TextView(context); 
one.setLayoutParams(params1); 
one.setText("some"); 
ll.addView(one); 

LinearLayout.LayoutParams params2 = params; 
params2.weight = 0.7f; 
TextView two = new TextView(context); 
two.setLayoutParams(params2); 
two.setText("word"); 
ll.addView(two); 

LinearLayout.LayoutParams params3 = params; 
params3.weight = 0.15f; 
TextView three = new TextView(context); 
three.setLayoutParams(params3); 
three.setText("here"); 
ll.addView(three); 

但在这种情况下,我获得三个TextView中的等宽。看起来我没有为主LL添加weightSum属性,但我不知道该怎么做...

请帮忙!

谢谢!

回答

4
  1. 偏好浮点数的整数。这样你就可以得到你想要的任何一种分数(甚至1/3)。

  2. 如果您设置了每个视图的权重,则不需要设置weightSum。

  3. 如果你设置了weightSum,你可以留下一个没有任何重量的视图,给它剩下的可用空间。

  4. 它看起来你给所有的意见相同的layoutparams,而不是克隆它们为每个人。当你使用“params2 = params;”时,这意味着你设置了一个参考,而不是你创建一个新的参考。在该方法的最后,所有将指向相同的layoutParams,权重为0.15f(因为这是最后一个)。

+0

谢谢您的回应!你的提示帮助了我。我错误的是克隆layoutparams。当我为每个TextView创建一个新的时,一切都很好。谢谢!!! – lubart

+0

欢迎您,我建议您观看Google IO视频。他们可以给你很多其他的提示。对于初学者,您还可以观看“新波士顿”视频。 –

+0

谢谢!我会做的! :) – lubart