转载 通过Java代码设置layout_weight

来源:互联网 发布:nsga2算法讲解 编辑:程序博客网 时间:2024/05/18 00:54

通过Java代码设置layout_weight

通过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);
原创粉丝点击