快速了解Android onMeasure() onLayout()

来源:互联网 发布:mac 批量保存网页图片 编辑:程序博客网 时间:2024/04/27 06:29

通过继承ViewGroup时一般都要重写onMeasure() onLayout()方法

@Overrideprotected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {//获取模式和大小,边界参数共有3种模式:UNSPECIFIED一般为0, EXACTLY准确尺寸, AT_MOST自适应尺寸  int w_mode = MeasureSpec.getMode(widthMeasureSpec);int w_size = MeasureSpec.getSize(widthMeasureSpec);int h_mode = MeasureSpec.getMode(heightMeasureSpec);int h_size = MeasureSpec.getSize(heightMeasureSpec);//计算自定义的所有子控件的大小   measureChildren(widthMeasureSpec, heightMeasureSpec);//通知父控件,宽高需要多大地方放置子控件//setMeasuredDimension(resolveSize(size, widthMeasureSpec),resolveSize(size, heightMeasureSpec));setMeasuredDimension(w_size, h_size);Log.e("onMeasure","宽mode=" + w_mode + "宽size="+ w_size+ "高mode=" + h_mode+ "高size=" +h_size);// super.onMeasure(widthMeasureSpec,heightMeasureSpec);}
//onLayout是为了指定视图的显示位置,方法执行的前后顺序是在onMeasure之后,因为视图肯定是只有知道大小才能指定位置放置

@Override      protected void onLayout(boolean changed, int l, int t, int r, int b) {          // 记录总高度          int mTotalHeight = 0;          // 遍历所有子视图          int childCount = getChildCount();          for (int i = 0; i < childCount; i++) {              View childView = getChildAt(i);              // 获取在onMeasure中计算的视图尺寸              int measureHeight = childView.getMeasuredHeight();              int measuredWidth = childView.getMeasuredWidth();                childView.layout(l, mTotalHeight, measuredWidth, mTotalHeight   + measureHeight);              mTotalHeight += measureHeight;          }      }

1 0
原创粉丝点击