zoukankan      html  css  js  c++  java
  • 当ViewGroup测量,以及为gone的时候怎么获取ViewGroup的高度

    1.测量时,需要自定义ViewGroup,实现onMeasure方法

       @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            int measuredWidth = 0;
            int measuredHeight = 0;
            final int childCount = getChildCount();
            measureChildren(widthMeasureSpec, heightMeasureSpec);
    
            int widthSpaceSize = MeasureSpec.getSize(widthMeasureSpec);
            int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
            int heightSpaceSize = MeasureSpec.getSize(heightMeasureSpec);
            int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
            if (childCount == 0) {
                setMeasuredDimension(0, 0);
            } else if (widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST) {
                final View childView = getChildAt(0);
                measuredWidth = childView.getMeasuredWidth() * childCount;
                measuredHeight = childView.getMeasuredHeight();
                setMeasuredDimension(measuredWidth, measuredHeight);
            } else if (heightSpecMode == MeasureSpec.AT_MOST) {
                final View childView = getChildAt(0);
                measuredHeight = childView.getMeasuredHeight();
                setMeasuredDimension(widthSpaceSize, childView.getMeasuredHeight());
            } else if (widthSpecMode == MeasureSpec.AT_MOST) {
                final View childView = getChildAt(0);
                measuredWidth = childView.getMeasuredWidth() * childCount;
                setMeasuredDimension(measuredWidth, heightSpaceSize);
            }
        }
    

     然后在调用this.getMeasuredHeight();就可以获取了。

     this.getMeasuredHeight();
    

     2.当view为gone的时候怎么获取view的高度

    在项目开发中,遇到了 当view为gone时 测量高度一直为0,解决办法:

    mView.getViewTreeObserver().addOnGlobalLayoutListener( 
        new OnGlobalLayoutListener(){
     
            @Override
            public void onGlobalLayout() {
                // gets called after layout has been done but before display
                // so we can get the height then hide the view    
     
                mHeight = mView.getHeight();  
     
                mView.getViewTreeObserver().removeOnGlobalLayoutListener(this);
                mView.setVisibility(View.GONE);
            }
     
    });
    

     默认先让他显示,而加载完成,则进行View.GONE,就可以了。

  • 相关阅读:
    Windows Server2016环境中安装Oracle12c数据库
    centos7 安装Oracle19C 数据库
    centos7 磁盘分区以及磁盘挂载
    PHP日常开发技巧散记
    代码压缩工具 webpack安装与入门使用【初级】
    程序员修炼之道系列 | 使用曳光弹找到目标
    程序员修炼之道系列 | 不要冲出前灯范围
    程序员修炼之道系列 | 敏捷估算
    程序员修炼之道系列 | “豆腐渣“工程竟然也能做原型
    官宣!禅道与极狐(GitLab)达成深度合作,携手推进开源开放DevOps生态
  • 原文地址:https://www.cnblogs.com/lixiangyang521/p/13092725.html
Copyright © 2011-2022 走看看