如何在代码中设置子权重?

时间:2012-01-01 11:02:06

标签: android android-widget

我希望该按钮(子)将具有水平LinearLayout(其父级)的全宽的25%。代码:

LinearLayout ll = new LinearLayout(this);
ll.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.FILL_PARENT));
ll.setWeightSum (1.0f);

Button b = new Button (this);
ll.addView(b);

我该怎么办?感谢。

2 个答案:

答案 0 :(得分:2)

试试这个:

    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENTS,LayoutParams.FILL_PARENT));
    lp.weight = 0.25;
    b.setLayoutParams(lp);

答案 1 :(得分:0)

您可以将其作为LinearLayout.LayoutParams构造函数的一部分传递:

LayoutParams param = new LinearLayout.LayoutParams(
                             LayoutParams.MATCH_PARENT,
                             LayoutParams.MATCH_PARENT, 1.0f);