通过Java code来设置View的layout_weight。
方法一:
LayoutParams param = new LinearLayout.LayoutParams(
LayoutParams.MATCH_PARENT,
LayoutParams.MATCH_PARENT, 1.0f);
然后:View.setLayoutParams(param),则这个View在它的LinearLayout的layout_weight为1.0f (表示1.0是浮点数,或者 (float)1.0)
方法二:
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
params.weight = 1.0f;
Button button = new Button(this);
button.setLayoutParams(params);
为什么会有方法二呢?因为有可能会通过new LinearLayout.LayoutParams来设置Gravity,比如:
leftArrow = new ImageButton(context);
lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,
LayoutParams.WRAP_CONTENT, Gravity.LEFT);
lp.weight = 1.0f;
leftArrow.setLayoutParams(lp);