Android Java 代码设置 layout_weight 属性

介绍

遇到在一个页面布局中,UI显示需要把屏幕分成上下两部分高度均分显示内容.是不是会想到 xml 里的 layout_weight设置权重的属性,但是现在需要代码里设置权重.
查了下,控件必须在 LinearLayout 中才能设置权重,下面就给出一个方法设置权重.

使用方法

方法一

我用的是这种,先看代码

        TextView topContentTextView=new TextView(this);
        topContentTextView.setGravity(Gravity.CENTER);
        topContentTextView.setTextSize(Axis.scaleTextSize(36));
        topContentTextView.getPaint().setFakeBoldText(true);
        topContentTextView.setTextColor(Color.BLACK);
        topContentTextView.setText(topStr01);
        topContentTextView.setLineSpacing(1,1);
        LinearLayout.LayoutParams topContentTextView_lp=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,0,1.0f);//此处我需要均分高度就在heignt处设0,1.0f即设置权重是1,页面还有其他一个控件,1:1高度就均分了  
        topView.addView(topContentTextView,topContentTextView_lp);

就是这个

LinearLayout.LayoutParams topContentTextView_lp=new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,0,1.0f);

注意点

原方法为

 public LayoutParams(int width, int height, float weight) {
            super((android.view.ViewGroup.LayoutParams)null);
            throw new RuntimeException("Stub!");
        }
  • 布局中设置的方向是horizontal,设置成LayoutParams(0,heignt,weight) 即width需要设置权重就在width处为0
  • 布局中设置的方向是vertical,设置成LayoutParams(width,0,weight) 即heignt需要设置权重就在heignt处为0

所以建议根据方向的不同,设置宽或者高为0

方法二

LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
    LayoutParams.WRAP_CONTENT, LayoutParams.FILL_PARENT);
params.weight = 1.0f;//在此处设置weight
Button button = new Button(this);
button.setLayoutParams(params);

有可能会通过new LinearLayout.LayoutParams来设置Gravity,比如

        leftArrow = new ImageButton(context);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT, Gravity.LEFT);
        lp.weight = 1.0f;
        leftArrow.setLayoutParams(lp);
  • 9
    点赞
  • 14
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值