上一篇简单说了下View的工作绘制原理,其中说到了几个重要的方法measure、layout、draw…这篇主要记录下自定义View这些方法的意思和使用。

一、onMeasure

测量View的大小,代码实现如下:

@Override  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec)  {      // super.onMeasure(widthMeasureSpec, heightMeasureSpec);      /**      * 设置宽度      */      int specMode = MeasureSpec.getMode(widthMeasureSpec);      int specSize = MeasureSpec.getSize(widthMeasureSpec);      if (specMode == MeasureSpec.EXACTLY)// match_parent , accurate      {            mWidth = specSize;      } else      {          // 由图片决定的宽          int desireByImg = getPaddingLeft() + getPaddingRight() + mImage.getWidth();          // 由字体决定的宽          int desireByTitle = getPaddingLeft() + getPaddingRight() + mTextBound.width();          if (specMode == MeasureSpec.AT_MOST)// wrap_content          {              int desire = Math.max(desireByImg, desireByTitle);              mWidth = Math.min(desire, specSize);           }      }      /***      * 设置高度      */      specMode = MeasureSpec.getMode(heightMeasureSpec);      specSize = MeasureSpec.getSize(heightMeasureSpec);      if (specMode == MeasureSpec.EXACTLY)// match_parent    {          mHeight = specSize;      } else      {          int desire = getPaddingTop() + getPaddingBottom() + mImage.getHeight() + mTextBound.height();          if (specMode == MeasureSpec.AT_MOST)// wrap_content          {              mHeight = Math.min(desire, specSize);          }      }      setMeasuredDimension(mWidth, mHeight);  }  

由代码见 用到了 specSize(测量的规格大小) 和 specMode(测量模式)。specSize 则就用于我们赋值宽高的大小,而specMode 则有三种模式:

类型 调用 描述
UNSPECIFIED MeasureSpec.UNSPECIFIED 父容器不对View有任何限制,要多大给多大,一般用于系统内部
EXACTLY MeasureSpec.EXACTLY 父容器已经测出并指定了View的大小,此时View的大小就是specSize所指定的值。对应的是LayoutParams中的math_parent
AT_MOST MeasureSpec.AT_MOST 父容器没有指定View的具体大小,View的大小看具体实现,但大小又不能大于父容器指定的specSize得限制

最后通过 setMeasuredDimension 设置宽高。设置后可以通过getMeasureWidth 和 getMeasureHeight 方法获取测量后的宽高。

二、onSizeChanged

确定View大小,并且在View的size改变后回调次方法。

@Override    protected void onSizeChanged(int w, int h, int oldw, int oldh) {        super.onSizeChanged(w, h, oldw, oldh);    }

三、onLayout

确定View在视图中的位置。这个方法有点特别,包含两个部分:一个是View,另一个是ViewGroup。分别看下源码:
View:

protected void onLayout(boolean changed, int left, int top, int right, int bottom) {}

ViewGroup:

@Override  protected abstract void onLayout(boolean changed, int l, int t, int r, int b); 

根据源码,可以看出,View的onlayout是一个空方法,ViewGroup是一个抽象方法,因为onLayout()过程是为了确定视图在布局中所在的位置,及父视图确定子View的位置,所以ViewGroup 的 onLayout 是一个抽象方法,每个继承ViewGroup的都要重写这个方法:

@Override      protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {          super.onMeasure(widthMeasureSpec, heightMeasureSpec);          if (getChildCount() > 0) {              View childView = getChildAt(0);              measureChild(childView, widthMeasureSpec, heightMeasureSpec);          }      }@Override      protected void onLayout(boolean changed, int l, int t, int r, int b) {          if (getChildCount() > 0) {              View childView = getChildAt(0);              childView.layout(0, 0, childView.getMeasuredWidth(), childView.getMeasuredHeight());          }      } 

在onLayout()过程结束后,我们就可以调用getWidth()方法和getHeight()方法来获取视图的宽高了。

上面说道的getMeasureWidth、getMeasureHeight 和 getWidth、getHeight 有什么区别呢?

1、getMeasureWidth()方法在measure()过程结束后就可以获取到了,而getWidth()方法要在layout()过程结束后才能获取到

2、getMeasureWidth()方法中的值是通过setMeasuredDimension()方法来进行设置的,而getWidth()方法中的值则是通过视图右边的坐标减去左边的坐标计算出来的

上面的代码,这里给子视图的layout()方法传入的四个参数分别是0、0、childView.getMeasuredWidth()和childView.getMeasuredHeight(),因此getWidth()方法得到的值就是childView.getMeasuredWidth() - 0 = childView.getMeasuredWidth() ,所以此时getWidth()方法和getMeasuredWidth() 得到的值就是相同的,但如果你将onLayout()方法中的代码进行如下修改:

@Override  protected void onLayout(boolean changed, int l, int t, int r, int b) {      if (getChildCount() > 0) {          View childView = getChildAt(0);          childView.layout(0, 0, 400, 400);      }  } 

这样getWidth()方法得到的值就是400 - 0 =
400,不会再和getMeasuredWidth()的值相同了。当然这种做法充分不尊重measure()过程计算出的结果,通常情况下是不推荐这么写的。

四、onDraw

绘制内容:

public class MyView extends View {    private PointF mPoint = new PointF(200, 200);    private Paint mPaint;    public MyView(Context context) {        this(context, null);    }    public MyView(Context context, @Nullable AttributeSet attrs) {        this(context, attrs, 0);    }    public MyView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {        super(context, attrs, defStyleAttr);        initView();    }    private void initView() {        mPaint = new Paint();        mPaint.setColor(Color.BLUE);        mPaint.setStyle(Paint.Style.FILL);        mPaint.setAntiAlias(true);    }    @Override    protected void onDraw(Canvas canvas) {        super.onDraw(canvas);        canvas.drawCircle(mPoint.x, mPoint.y, 100, mPaint);    }}

上面是一个简单绘制了一个圆。绘图主要用到了Canvas(画布) Paint(涂料)

Canvas 的一些主要方法:

 - drawPath() - drawLine() - drawRect() - drawCircle() - drawOval() - drawArc() - drawPoint() - drawBirmap() - drawText()

Paint 的一些主要方法:

  setAntiAlias();             //设置画笔的锯齿效果 setColor();                 //设置画笔的颜色 setARGB();                  //设置画笔的A、R、G、B值 setAlpha();                 //设置画笔的Alpha值 setTextSize();              //设置字体的尺寸 setStyle();                  //设置画笔的风格(空心或实心) setStrokeWidth();            //设置空心边框的宽度 getColor();                  //获取画笔的颜色

———————————绘制方法和刷新方法的分割线—————————————


一、requestLayout

该方法的调用,会让View树重新进行一次onMeasure、onLayout、(onDraw)的过程。至于onDraw 会不会被调用有个小说明:

requestLayout如果没有改变l,t,r,b,那就不会触发onDraw;但是如果这次刷新是在动画里,mDirty非空,就会导致onDraw

二、invalidate

该方法的调用,会让View树重新执行onDraw方法,需要在主线程(UI线程)中使用。

二、postInvalidate

该方法和 invalidate 的作用是一样的,都会是View执行onDraw,不同的是,postInvalidate 是在非UI线程中使用。


总结

自定义View篇:

  • Android 自定义View(一)原理
  • Android 自定义View(二)方法分析

更多相关文章

  1. Android(安卓)单例模式与SharedPreferences一起使用
  2. android Service深入详解
  3. Android(安卓)premission 访问权限代码
  4. [Android]Service和Activity双向通信的两种方式
  5. dalvik.vm 属性与android:largeHeap
  6. Android利用Soap读取WebService并且解析XML的DataSet数据
  7. 横竖屏切换不重启activity的方法
  8. Fragment加载轮换add,show,hide,replace方法
  9. Android(安卓)NDK c创建java对象

随机推荐

  1. Android的开篇
  2. Android(安卓)架构大致分析
  3. Android嵌入式开发初学者的几个注意点
  4. Android(安卓)Support 包里究竟有什么
  5. Android(安卓)的网络编程(12)-Android定
  6. Android启动方式简述
  7. [置顶] android中通过自定义xml实现你需
  8. Android(安卓)Studio利用Gradle删除没有
  9. Android虚拟设备访问WebSocket问题
  10. android键盘表情流畅切换实现