0

在我的 Android 应用程序中,我需要动态创建一些带有文本的 LinearLayout。

但我不能设置每个元素的权重。我希望 LL 在 XML 部分看起来像:

<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。看起来我没有weightSum为主 LL 添加属性,但我不知道该怎么做。

4

1 回答 1

4
  1. 更喜欢 integer 而不是 float 。这样你就可以得到任何你想要的分数(甚至是 1/3)。

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

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

  4. it seems you give all of the views the same layoutparams instead of cloning it for each of them . when you use "params2 = params;" , it means that you set a reference to it and not that you create a new one . in the end of the method , all will point to the same layoutParams , with the weight of 0.15f (since that's the last one) .

于 2012-06-01T10:43:13.300 回答