28

我想以编程方式将三个线性布局添加到每个宽度相同的活动中。问题是我无法以编程方式设置这些布局的权重。我可以在 xml 中执行此操作,但我想在程序中执行此操作。这就是我想要的: 在此处输入图像描述

4

4 回答 4

57

这是解决方案

    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, 100);
    lp.weight = 1;

查看完整解决方案

LinearLayout ll1, ll2, ll3;
    /* Find these LinearLayout by ID 
     i.e ll1=(LinearLayout)findViewById(R.id.ll1);
     */

    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(0, 100);
    lp.weight = 1;
    ll1.setLayoutParams(lp);
    ll2.setLayoutParams(lp);
    ll3.setLayoutParams(lp);
于 2013-10-03T12:00:06.023 回答
7

在为子视图设置布局参数时用于new LinearLayout.LayoutParams(int width, int height, float weight)设置权重

于 2013-10-03T11:47:17.017 回答
3

您可以通过为各个线性布局设置布局权重属性来实现,将其传递给 LinearLayout - LayoutParams 构造函数:

LinearLayout.LayoutParams param = new LinearLayout.LayoutParam(
                         LayoutParams.MATCH_PARENT,
                         LayoutParams.MATCH_PARENT, 1);

或者

LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(
                         0,
                         LayoutParams.MATCH_PARENT, 1);

希望它可以帮助你!

于 2013-10-03T12:29:34.827 回答
3

这样做。。

protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    txtNote = (LinedEditText) findViewById(R.id.txtNote);
    lnr = (LinearLayout) findViewById(R.id.lnr);
    LinearLayout l1 = new LinearLayout(this);
    LinearLayout l2 = new LinearLayout(this);
    LinearLayout l3 = new LinearLayout(this);
    l1.setBackgroundResource(android.R.color.holo_green_light);
    l2.setBackgroundResource(android.R.color.holo_orange_dark);
    l3.setBackgroundResource(android.R.color.holo_blue_bright);

    LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(0,LinearLayout.LayoutParams.MATCH_PARENT, 1);
    lnr.addView(l1, param);
    lnr.addView(l2, param);
    lnr.addView(l3, param);

}
于 2013-10-03T12:06:26.970 回答