为什么要自定义View?
Android系统提供了一系列的原生控件,但这些原生控件并不能够满足我们的需求时,我们就需要自定义View了。
自定义View流程
一般来说,自定义view要重写onMeasure()以及onDraw()这两个方法。看方法名字就知道,onMeasure()是负责测量控件的大小,onDraw()方法是负责将控件画出来。
onMeasure方法
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
在这个方法中,一共有两个参数。这两个参数分别表示控件宽高的大小以及测量模式,两个都是32位的int型数据,其中前面2位表示测量模式,后两位表示控件的大小。谷歌已经封装好方法给我们,可以直接通过方法即可获取测量模式以及大小。
//获取测量模式
int mode = MeasureSpec.getMode(widthMeasureSpec);
//获取大小
int size = MeasureSpec.getSize(widthMeasureSpec);
测量模式一种有3种
测量模式 | 含义 |
---|---|
EXACTLY | 父容器检测出view精确的大小,view最终大小为测量的大小 |
AT_MOST | 父容器指定了view的最大值,view的大小不可以超过这个最大值 |
UNSPECIFIED | 父容器对view没有限制,view本身想要多大就多大 |
测量模式跟我们平时开发在布局文件中写的match_parent、wrap_content有什么关系呢?
match_parent对应的是EXACTLY.我们怎么理解呢?其实很简单,我们布局里面写match_parent表示的是撑满父布局的剩余空间。父布局的剩余空间是确定的,因此是view的大小是一个确定的值,所以是EXACTLY.
wrap_content对应的是AT_MOST.我们在布局中使用wrap_content的意思是包裹控件的内容。但是这个时候父控件大小是不确定的,自然子view占用的大小也是不确定的。但是怎么理解父布局给出的建议大小呢?事实上,父布局给出的建议大小其实就是父布局可以获取的最大的大小。具体为什么,可以参考View的绘制流程一文,在这里不讨论。
关于测量模式可以参考此文:Android View的绘制流程
重写onMeasure方法
我们理论说得再多还不如动手实践一次,那就直接Show The Code No BB.
我们简单绘制一个圆形的view。
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
int width = getViewSize(100, widthMeasureSpec);
int height = getViewSize(100, heightMeasureSpec);
if (width < height) {
height = width;
} else {
width = height;
}
setMeasuredDimension(width, height);
}
private int getViewSize(int defaultSize, int measureSpec) {
int resultSize = defaultSize;
int size = MeasureSpec.getSize(measureSpec);
int mode = MeasureSpec.getMode(measureSpec);
switch (mode) {
case MeasureSpec.EXACTLY:
resultSize = size;
break;
case MeasureSpec.AT_MOST:
resultSize = size;
break;
case MeasureSpec.UNSPECIFIED:
resultSize = defaultSize;
break;
}
return resultSize;
}
布局如下:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<com.example.mazhi.customview.MyView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:view_color="@color/colorAccent" />
</android.support.constraint.ConstraintLayout>
在布局中,我们view是wrap_content的,因此父布局给我们的测量模式一定是AT_MOST,size一定就是屏幕的宽度。我们在这里要实现的是一个正方形,因此width以及height设置了相等。其他的就不多解释了,大家一看就懂。
重写onDraw方法
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
//半径
int r = getMeasuredHeight() / 2;
canvas.drawCircle(r, r, r, paint);
}
算出半径以及圆心,直接调用api即可,没什么难的,也不多解释了吧。
总结一下,简单的自定义view可以直接重写onMeasure方法以及onDraw方法即可。onMeasure方法负责测量view的大小,onDraw方法复制绘制。