android--View自定义基础

来源:互联网 发布:apache 插件开发 编辑:程序博客网 时间:2024/05/16 09:25

view的绘制过程:
一:Measure:

protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {    setMeasuredDimension(getDefaultSize(getSuggestedMinimumWidth(), widthMeasureSpec),            getDefaultSize(getSuggestedMinimumHeight(), heightMeasureSpec));}protected final void setMeasuredDimension(int measuredWidth, int measuredHeight) {boolean optical = isLayoutModeOptical(this);if (optical != isLayoutModeOptical(mParent)) {        Insets insets = getOpticalInsets();int opticalWidth  = insets.left + insets.right;int opticalHeight = insets.top  + insets.bottom;        measuredWidth  += optical ? opticalWidth  : -opticalWidth;        measuredHeight += optical ? opticalHeight : -opticalHeight;    }    setMeasuredDimensionRaw(measuredWidth, measuredHeight);}public static int getDefaultSize(int size, int measureSpec) {int result = size;int specMode = MeasureSpec.getMode(measureSpec);int specSize = MeasureSpec.getSize(measureSpec);switch (specMode) {case MeasureSpec.UNSPECIFIED:        result = size;break;case MeasureSpec.AT_MOST:case MeasureSpec.EXACTLY:        result = specSize;break;    }return result;}

其中setMeasuredDimension()方法,设置了measure过程中View的宽高,getSuggestedMinimumWidth()返回View的最小Width,Height也有对应的方法。插几句,MeasureSpec类是View类的一个内部静态类,它定义了三个常量UNSPECIFIED、AT_MOST、EXACTLY,其实我们可以这样理解它,它们分别对应LayoutParams中match_parent、wrap_content、xxxdp。我们可以重写onMeasure来重新定义View的宽高!

二:Layout:

* @param changed This is a new size or position for this view * @param left Left position, relative to parent * @param top Top position, relative to parent * @param right Right position, relative to parent * @param bottom Bottom position, relative to parentprotected void onLayout(boolean changed, int left, int top, int right, int bottom) {}

三:Draw

/** * Implement this to do your drawing. * * @param canvas the canvas on which the background will be drawn */protected void onDraw(Canvas canvas) {}

四:View中还有三个比较重要的方法

requestLayout
View重新调用一次layout过程。
invalidate
View重新调用一次draw过程
forceLayout
标识View在下一次重绘,需要重新调用layout过程。
onSizeChanged() 这个方法在界面的尺寸更改的时候会被调用,一般是在屏幕旋转的时候会被调用,有两个新w/h和旧w/h会被传入!

五:自定义view的时候,通常需要实现三个不同参数的方法:
第一个方法,一般我们这样使用时会被调用,View view = new View(context);
第二个方法,当我们在xml布局文件中使用View时,会在inflate布局时被调用,

<View layout_width="match_parent" layout_height="match_parent"/>

第三个方法,跟第二种类似,但是增加style属性设置,这时inflater布局时会调用第三个构造方法。

0 0