欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 运维知识 > Android >内容正文

Android

Android Java 代码设置 layout_weight 属性

发布时间:2024/4/15 Android 47 豆豆
生活随笔 收集整理的这篇文章主要介绍了 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);

总结

以上是生活随笔为你收集整理的Android Java 代码设置 layout_weight 属性的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。