How to set layout_weight attribute dynamically fro

2019-01-02 20:28发布

How can I set the value for the attribute layout_weight for button in android dynamically from java code ?

9条回答
余生无你
2楼-- · 2019-01-02 20:50

If the constructor with width, height and weight is not working, try using the constructor with width and height. And then manually set the weight.

And if you want the width to be set according to the weight, set width as 0 in the constructor. Same applies for height. Below code works for me.

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);
childParam1.weight = 0.7f;
child2.setLayoutParams(childParam2);

parent.setWeightSum(1f);
parent.addView(child1);
parent.addView(child2);
查看更多
千与千寻千般痛.
3楼-- · 2019-01-02 20:52

If I someone looking for answer, use this:

LinearLayout.LayoutParams lay = (LinearLayout.LayoutParams) myLayout.getLayoutParams();
lay.weight = 0.5;

If you are initializing your layout from xml file, this will be much more convenient than providing new layout parameters for Linear Layout.

查看更多
流年柔荑漫光年
4楼-- · 2019-01-02 20:57

If layoutparams is already defined (in XML or dynamically), Here's a one liner:

((LinearLayout.LayoutParams) mView.getLayoutParams()).weight = 1;
查看更多
登录 后发表回答