接下来就是我们平时自定义 View 经常要重写的三大方法了,先看 onMeasure()
#RefreshView.java
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
if (widthMode == MeasureSpec.AT_MOST && heightMode == MeasureSpec.EXACTLY) {
setMeasuredDimension(mWidth, heightSize);
} else if (widthMeasureSpec == MeasureSpec.EXACTLY && heightMeasureSpec == MeasureSpec.AT_MOST) {
setMeasuredDimension(widthSize, mHeight);
} else if (widthMode == MeasureSpec.EXACTLY && heightMode == MeasureSpec.EXACTLY) {
setMeasuredDimension(widthSize, heightSize);
} else {
setMeasuredDimension(mWidth, mHeight);
}
}
为了适配布局文件中的 wrap_content 参数,我们需要重写此方法(此方法不是本文的研究重点,不明白的可以百度或者google
一下,或者参考《Android开发艺术探索》里面的相关章节)。
接着看 onLayout() 方法:
#RefreshView.java
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
initContentAttr(getMeasuredWidth(), getMeasuredHeight());
resetCircles();
}
在此方法中调用了 initContentAttr() 方法来初始化内容大小与 resetCircles() 来初始化(重置)三个小球的属性。分别看下这两
个方法:
#RefreshView.java
private void initContentAttr(int width, int height) {
mContentWidth = width - getPaddingLeft() - getPaddingRight();
mContentHeight = height - getPaddingTop() - getPaddingBottom();
}
这方法很简单,就是进行了 padding 的处理,得出真正的布局大小。如果不处理 padding 的话那么用户设置了 padding 将失
效。再看 resetCircles():
#RefreshView.java
public static final int STATE_ORIGIN = 0;
public static final int STATE_PREPARED = 1;
private int mOriginState = STATE_ORIGIN;
private void resetCircles() {
if (mCircles.isEmpty()) {
int x = mContentWidth / 2;
int y = mContentHeight / 2;
mGap = x - mMinRadius; //初始化相邻圆心间的最大间距
Circle circleLeft = new Circle(x, y, mMinRadius, 0xffff7f0a);
Circle circleCenter = new Circle(x, y, mMaxRadius, Color.RED);
Circle circleRight = new Circle(x, y, mMinRadius, Color.GREEN);
mCircles.add(LEFT, circleLeft);
mCircles.add(RIGHT, circleRight);
mCircles.add(CENTER, circleCenter);
}
if (mOriginState == STATE_ORIGIN) {
int x = mContentWidth / 2;
int y = mContentHeight / 2;
for (int i = 0; i < mCircles.size(); i++) {
Circle circle = mCircles.get(i);
circle.x = x;
circle.y = y;