【问题标题】:How to add weightSum attribute for main LL?如何为主 LL 添加 weightSum 属性?
【发布时间】:2012-06-06 13:47:37
【问题描述】:

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

【问题讨论】:

    标签: java android positioning


    【解决方案1】:
    1. 更喜欢整数而不是浮点数。这样你就可以得到任何你想要的分数(甚至是 1/3)。

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

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

    4. 您似乎为所有视图提供了相同的布局参数,而不是为每个视图克隆它。当您使用“params2 = params;”时,这意味着您设置了对它的引用,而不是创建新的引用。在方法的最后,all 将指向相同的 layoutParams,权重为 0.15f(因为这是最后一个)。

    【讨论】:

    • 感谢您的重播!你的建议帮助了我。我的错误在于克隆布局参数。当我为每个 TextView 创建新的时,一切都很好。谢谢!!!
    • 不客气,我建议您观看 google IO 视频。他们可以给你很多其他的提示。对于初学者,您还可以观看“新波士顿”视频。
    猜你喜欢
    • 1970-01-01
    • 2011-09-16
    • 2015-01-26
    • 2017-09-20
    • 1970-01-01
    • 2021-10-28
    • 2015-02-09
    • 2011-12-29
    • 2016-11-16
    相关资源
    最近更新 更多