View绘制流程

来源:互联网 发布:淘宝刷单新规则影响 编辑:程序博客网 时间:2024/05/21 00:46

一、measure()过程
measure函数原型为 View.java 该函数不能被重载

public final void measure(int widthMeasureSpec, int heightMeasureSpec) {      //....      //回调onMeasure()方法        onMeasure(widthMeasureSpec, heightMeasureSpec);      //more  }  

所以我们在自定义View时只需重载maesure()方法里面的 onMeasure(widthMeasureSpec, heightMeasureSpec); 方法即可。
用伪代码描述该measure流程:

//回调View视图里的onMeasure过程  private void onMeasure(int height , int width){   //设置该view的实际宽(mMeasuredWidth)高(mMeasuredHeight)   //1、该方法必须在onMeasure调用,否者报异常。   setMeasuredDimension(w , h) ;   //2、如果该View是ViewGroup类型,则对它的每个子View进行measure()过程   int childCount = getChildCount() ;   for(int i=0 ;i<childCount ;i++){    //2.1、获得每个子View对象引用    View child = getChildAt(i) ;    //整个measure()过程就是个递归过程    //该方法只是一个过滤器,最后会调用measure()过程 ;或者 measureChild(child , w, h)方法都    measureChildWithMargins(child , w, h) ;     //其实,对于我们自己写的应用来说,最好的办法是去掉框架里的该方法,直接调用view.measure(),如下:    //child.measure(w, h)   }  }  //该方法具体实现在ViewGroup.java里 。  protected  void measureChildWithMargins(View v, int width , int height){   v.measure(w,h)     }  

在 onMeasure()方法里:
(1)如果是View重写setMeasuredDimension(h , l)即可
(2)如果是ViewGroup则重写setMeasuredDimension(w , h),并且测量子View的宽高。测量子view的方式有:

    getChildAt(int index).可以拿到index上的子view。    通过getChildCount得到子view的数目,再循环遍历出子view。   接着,subView.measure(int wSpec, int hSpec); //使用子view自身的测量方法或者调用viewGroup的测量子view的方法:   //某一个子view,多宽,多高, 内部加上了viewGroup的padding值   measureChild(subView, int wSpec, int hSpec);    //所有子view 都是 多宽,多高, 内部调用了measureChild方法   measureChildren(int wSpec, int hSpec);   //某一个子view,多宽,多高, 内部加上了viewGroup的padding值、margin值和传入的宽高wUsed、hUsed     measureChildWithMargins(subView, intwSpec, int wUsed, int hSpec, int hUsed); 
0 0
原创粉丝点击