您的位置:首页 > 其它

第4章 View的工作原理

2016-02-19 14:06 309 查看
View的工作流程:

measure:测量,确定View的测量宽/高;
layout:确定View的最终宽高和四个定点的位置;
draw:将View绘制到屏幕上;

View的measure:
直接继承VIew的自定义控件需要重写onMeasure方法并设置wrap_content时的自身大小,否则在布局文件中使用wrap_content就相当于使用match_parent。
因为MeasureSpec包含有SpecMode(测量模式)和SpecSize(某种测量模式下的规格大小)两个参数。

protectedvoid onMeasure(int widthMeasureSpec,int heightMeasureSpec){
  super.onMeasure(widthMeasureSpec,heightMeasureSpec);
  int widthSpecMode =MeasureSpec.getMode(widthMeasureSpec);
  int widthSpecSize =MeasureSpec.getSize(widthMeasureSpec);
  int heightSpecMode =MeasureSpec.getMode(heightMeasureSpec);
  int heightSpecSize =MeasureSpec.getSize(heightMeasureSpec);
  if(widthSpecMode ==MeasureSpec.AT_MOST && heightSpecMode ==MeasureSpec.AT_MOST){
    setMeasuredDimension(mWidth,mHeight);
  }else if(widthSpecMode ==MeasureSpec.AT_MOST){
    setMeasuredDimension(mWidth,heightSpecSize);
  }else if(heightSpecMode ==MeasureSpec.AT_MOST){
    setMeasuredDimmension(widthSpecSize,mHeight);
}
}


SpecMode三类:
1、UNSPECIFIED:父容器不对View有任何限制;
2、EXACITY:父容器已检测出View所需的精确大小;
3、AT_MOST:父容器已指定了一个可用大小,View的大小不能大于这个值。

在Activity的生命周期里onCreate,onResume里获取View的宽高可能得不到正确的值。解决方法:
(1)在onWindowFocusChanged方法里View已经初始化完毕,Activity的窗口得到焦点和失去焦点都会被调用。
这里测量的值是准确的。

width = view.getMeasuredWidth();


(2)view.post(runnable)
post可将runnable投递到消息队列尾部,然后等待Looper调用runnable,View已初始化好了。

protectedvoid onStart(){
  super.onStart();
  view.post(newRunnable()){
  @override
  publicvoid run(){
    int width = view.getMeasuredWidth();
    int height = view.getMeasureHeight();
    }
  });
}


(3)ViewTreeObserver

(4)使用measure方法手动测量

View的layout:
viewGroup会遍历所有子元素并调用setChildFrame来为子元素指定对应的位置,子元素又通过自己的layout方法来确定自己的位置。
View的测量宽/高和最终宽/高相等的,不过测量形成于View的measure过程,最终宽高形成于layout过程。

View的draw:
步骤:
(1)绘制背景background.draw(canvas)
(2)绘制自己(onDraw)
(3)绘制children(dispatchDraw)
(4)绘制装饰(onDrawScrollBars)

自定义View:
注意事项:
1、支持wrap_content,否则等同于match_parent;
2、支持padding(在onDraw的时候记得把padding加进去);
3、不在view里面用handler,view本身提供post系列方法;
4、view中我线程或动画及时停止,否则会造成内存溢出;
5、滑动嵌套冲突的解决;
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: