我如何从java代码动态设置属性layout_weight在android按钮的值?


当前回答

如果带有width、height和weight的构造函数不起作用,请尝试使用带有width和height的构造函数。然后手动设置权重。

如果您希望根据权重设置宽度,则在构造函数中将width设置为0。身高也是一样。 下面的代码为我工作。

LinearLayout.LayoutParams childParam1 = new LinearLayout.LayoutParams(0,LinearLayout.LayoutParams.MATCH_PARENT);
childParam1.weight = 0.3f;
child1.setLayoutParams(childParam1);

LinearLayout.LayoutParams childParam2 = new LinearLayout.LayoutParams(0,LinearLayout.LayoutParams.MATCH_PARENT);
childParam2.weight = 0.7f;
child2.setLayoutParams(childParam2);

parent.setWeightSum(1f);
parent.addView(child1);
parent.addView(child2);

其他回答

如果带有width、height和weight的构造函数不起作用,请尝试使用带有width和height的构造函数。然后手动设置权重。

如果您希望根据权重设置宽度,则在构造函数中将width设置为0。身高也是一样。 下面的代码为我工作。

LinearLayout.LayoutParams childParam1 = new LinearLayout.LayoutParams(0,LinearLayout.LayoutParams.MATCH_PARENT);
childParam1.weight = 0.3f;
child1.setLayoutParams(childParam1);

LinearLayout.LayoutParams childParam2 = new LinearLayout.LayoutParams(0,LinearLayout.LayoutParams.MATCH_PARENT);
childParam2.weight = 0.7f;
child2.setLayoutParams(childParam2);

parent.setWeightSum(1f);
parent.addView(child1);
parent.addView(child2);

如果你已经在你的layout(xml)文件中定义了你的视图,只想通过编程改变权重,这种方法更好

LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)   
mButton.getLayoutParams();
params.weight = 1.0f;
mButton.setLayoutParams(params);

new a LayoutParams会覆盖xml文件中定义的其他参数,比如页边距,或者你需要在LayoutParams中指定所有的参数。

我已经通过添加这行代码完成了我的任务!

LinearLayout.LayoutParams mylayout = (LinearLayout.LayoutParams)   
myview.getLayoutParams();
mylayout.weight = 2;
myview.setLayoutParams(mylayout);

任何线性布局。LayoutParams和TableLayout。LayoutParams对我有用,对于按钮右边的是taberlow。LayoutParams。那就是:

            TableRow.LayoutParams buttonParams = new TableRow.LayoutParams(
                    TableRow.LayoutParams.MATCH_PARENT,
                    TableRow.LayoutParams.WRAP_CONTENT, 1f);

关于使用MATCH_PARENT或WRAP_CONTENT是相同的。

使用LinearLayout。LayoutParams:

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
    LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT);
params.weight = 1.0f;
Button button = new Button(this);
button.setLayoutParams(params);

编辑:啊,埃里克的答案更简单!