0. 前言
自定义View
1. 直接继承View
构造器
例子
// 第一种写法,不需要自定义属性
public MyView(Context context) {
this(context, null);
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
initPaints(); // 初始化画笔
}
// 第二种写法,主要用于自定义属性
public MyView(Context context) {
this(context, null);
}
public MyView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MyView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
/*
* 解析自定义属性并做相应处理
*/
initPaints(); // 初始化画笔
}
onMeasure()方法
注:直接继承View 的自定义控件需要重写 onMeasure() 方法并设置 wrap_content 时的自身大小。
例子
// 第一种写法
protected void onMeasure(int widthMeasureSpec, int heigthMeasureSpec) {
int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSpecMode = MeasureSpec.getMode(heigthMeasureSpec);
int heightSpecSize = MeasureSpec.getSize(heigthMeasureSpec);
if (widthSpecMode == MeasureSpec.AT_MOST &&
heightSpecMode == MeasureSpec.AT_MOST) { // 宽高均为wrap_content
setMeasuredDimension(mWidth, mHeight);
} else if (widthSpecMode == MeasureSpec.AT_MOST) { // 宽为wrap_content,高为固定大小或match_parent
setMeasuredDimension(mWidth, heightSpecSize);
} else if (heightSpecMode == MeasureSpec.AT_MOST) { // 高为wrap_content,宽为固定大小或match_parent
setMeasuredDimension(widthSpecSize, mHeight);
} else { // 宽高均为固定大小或match_parent
setMeasuredDimension(widthSpecSize, heightSpecSize);
}
}
// 第二种写法
protected void onMeasure(int widthMeasureSpec, int heigthMeasureSpec) {
int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
int heightSpecMode = MeasureSpec.getMode(heigthMeasureSpec);
int heightSpecSize = MeasureSpec.getSize(heigthMeasureSpec);
if (widthSpecMode == MeasureSpec.EXACTLY &&
heightSpecMode == MeasureSpec.EXACTLY) { // 宽高均为固定大小或match_parent
setMeasuredDimension(widthSpecSize, heightSpecSize);
} else if (widthSpecMode == MeasureSpec.EXACTLY) { // 宽为固定大小或match_parent,高为wrap_content
setMeasuredDimension(widthSpecSize, mHeight);
} else if (heightSpecMode == MeasureSpec.EXACTLY) { // 高为固定大小或match_parent,宽为wrap_content
setMeasuredDimension(mWidth, heightSpecSize);
} else { // 宽高均为wrap_content
setMeasuredDimension(mWidth, mHeight);
}
}
/*
* 在上面的代码中,我们需要给View指定一个默认的内部宽和高(即mWidth和mHeight)并在wrap_content时设置此宽和高即可。
* 至于这个默认的内部宽和高的大小如何指定,这个没有固定的依据,根据需要灵活指定即可。
* 对于非wrap_content情形(即固定大小或match_parent),沿用系统的测量值(widthSpecSize或heightSpecSize)即可。
*
*/
onDraw()方法
自定义最主要的绘制就在这个方法中进行。涉及Cavas、Paint和Path等画图类。
注:需要在onDraw()方法中处理padding
自定义属性
第一步:创建res/values/attrs.xml
例子
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyView">
<attr name="circle_color" format="color"/>
<declare-styleable/>
<resources/>