介绍
遇到在一个页面布局中,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);