android 动态设置View的高度和宽度,ViewTreeObserver使用

private int mMonitorHeight = 0;
private int mMonitorWidth = 0;
private boolean  bisSetScreen = false;

 动态设置满屏宽度

 

ViewTreeObserver vto2 = monitor.getViewTreeObserver();
vto2.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener(){
    @Override
    public void onGlobalLayout(){
        if(bisSetScreen == false){
            mMonitorHeight = monitor.getMeasuredHeight();
            mMonitorWidth = monitor.getWidth();

            if(mMonitorHeight != 0 && mMonitorWidth != 0){
                monitor.setScreenSize(mMonitorWidth, mMonitorHeight);

                bisSetScreen = true;
            }
        }
    }
});

LinearLayout.LayoutParams linearParams =(LinearLayout.LayoutParams) TextView.getLayoutParams(); //取控件textView当前的布局参数

linearParams.width = 40;// 控件的宽强制设成30
linearParams.height =40;// 控件的高强制设成20

TextView.setLayoutParams(linearParams);

/**
 * 重设 view 的宽高
 */
public static void setViewLayoutParams(View view, int nWidth, int nHeight) {
    ViewGroup.LayoutParams lp = view.getLayoutParams();
    if (lp.height != nHeight || lp.width != nWidth) {
        lp.width = nWidth;
        lp.height = nHeight;
        view.setLayoutParams(lp);
    }
}

自动属性长度

ViewGroup.LayoutParams.WRAP_CONTENT
ViewGroup.LayoutParams.MATCH_PARENT

 控件的边距

RelativeLayout.LayoutParams linearParams2 =(RelativeLayout.LayoutParams) top2.getLayoutParams(); //取控件textView当前的布局参数
linearParams2.topMargin =450;// 控件的边距
top2.setLayoutParams(linearParams2);

动态设置列表高度

LinearLayout.LayoutParams linearParams =(LinearLayout.LayoutParams) activityOneRecyclerView.getLayoutParams(); //取控件textView当前的布局参数
linearParams.height = UIUtils.dip2px(98)*6;//98是item高度。6是item数量

工具方法:

/**
 * 将dip或dp值转换为px值,保证尺寸大小不变
 */
public static int dip2px(Context context, float dipValue) {
    final float scale = context.getResources().getDisplayMetrics().density;
    return (int) (dipValue * scale + 0.5f);
}
  • 7
    点赞
  • 11
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值