相关的方法:

1、集成view
2、实现3个构造方法(新版本是4个)
3、重写onMeasure,onLayout,onDraw方法

构造方法:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
public MyCustomView(Context context) {
this(context, null);//在代码中直接new一个Custom View实例的时候,会调用第一个构造函数.
}
/**
* 第二个构造函数
*/
public MyCustomView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
//在xml布局文件中调用Custom View的时候,会调用第二个构造函数
}
/**
* 第三个构造函数
*/
public MyCustomView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// 获取自定义属性,defStyle,attrs
}

//程序在运行时维护了一个 TypedArray的池,
// 程序调用时,会向该池中请求一个实例,用完之后,
// 调用 recycle() 方法来释放该实例,从而使其可被其他模块复用。
TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.MKLoader);
loaderView.setColor(typedArray.getColor(R.styleable.MKLoader_mk_color, Color.parseColor("#ffffff")));
typedArray.recycle();

onMeasure

设置自己的宽高

1
2
最后要设置,不然就是没有效果的   
setMeasuredDimension(measuredWidth, measuredHeight);

onLayout

计算位置,这里view的大小有了,可以使用getWidth(), getHeight()
可以设置动画操作

onDraw

真正画图

1
2
3
4
5
//旋转画图,先保存初始值,画,恢复初始值,再画,这样方便计算,不会乱
canvas.save();//保存画布现场
canvas.rotate(45 * i, center.x, center.y);//旋转画布,每个点相聚45度,8个点 360度
circles[i].draw(canvas);//画点
canvas.restore();//恢复画布,下一次就是旋转90度可以

invalidate

手动调用重绘

动画

1
2
3
4
5
6
7
8
9
10
11
12
13
//动画属性 从126 到 255 到 126 变化  渐变alpha值
ValueAnimator fadeAnimator = ValueAnimator.ofInt(126, 255, 126);
fadeAnimator.setRepeatCount(ValueAnimator.INFINITE);
fadeAnimator.setDuration(1000);
fadeAnimator.setStartDelay(index * 120);//后面的点比前一个点慢一点变化,就会有一个视觉差
fadeAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override public void onAnimationUpdate(ValueAnimator animation) {
circles[index].setAlpha((int)animation.getAnimatedValue());
invalidateListener.reDraw();//调用重绘
}
});

fadeAnimator.start();//开始动画

代码

有注解的代码