码迷,mamicode.com
首页 > 移动开发 > 详细

快速了解Android onMeasure() onLayout()

时间:2015-06-18 15:29:54      阅读:159      评论:0      收藏:0      [点我收藏+]

标签:android   onmeasure   onlayout   

通过重写ViewGroup学习onMeasure() onLayout()方法

@Override

protected 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;  
        }  
    }

快速了解Android onMeasure() onLayout()

标签:android   onmeasure   onlayout   

原文地址:http://blog.csdn.net/a704755096/article/details/46546969

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!