Android Java 代码设置 layout_weight 属性
生活随笔
收集整理的這篇文章主要介紹了
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 属性的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Android Activity Lau
- 下一篇: Android Studio 设置编辑器