一、View绘制流程
1、流程
- measure:确定View的测量宽高
- layout:根据测量的宽高确定View在其父View中的四个顶点的位置
- draw:将view绘制到屏幕上
2、三种测量模式
MeasureSpec 表示的是一个 32 位的整数值,它的高 2 位表示测量模式 SpecMode,低 30 位表示某种测量模式下的规格大小 SpecSize。
三种测量模式
EXACTLY:精确测量模式,当该视图的 layout_width 或者 layout_height 指定为具体数值或者 match_parent 时生效,表示父视图已经决定了子视图的精确大小,这种模式下 View 的测量值就是 SpecSize 的值。
AT_MOST:最大值模式,当前视图的 layout_width 或者 layout_height 指定为 wrap_content 时生效,此时子视图的尺寸可以是不超过父视图运行的最大尺寸的任何尺寸。
UNSPECIFIED:不指定测量模式,父视图没有限制子视图的大小,子视图可以是想要的任何尺寸,通常用于系统内部,应用开发中很少使用到。
3、getMeasureWidth()与getWidth()区别
一个View 的大小是由View本身和父View两个共同决定
getMeasureWidth:measure阶段确定,是xml中的原始值
getWidth:layout阶段确定,是最终显示的大小
两个值可能相等,可能不相等
如何在onCreate中获取View的高度?
- postDelay延迟获取一下
- ViewTreeObserver方式获取
ViewTreeObserver vto = view.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {
@Override
public void onGlobalLayout() {
view.getViewTreeObserver().removeGlobalOnLayoutListener(this);
Log.i(TAG, "width: " + view.getWidth());
Log.i(TAG, "height: " + view.getHeight());
}
});
4、View,ViewGroup绘制区别
onMeasure:
View只需要确定自己的大小就可,ViewGroup需要先确定子View的大小
onLayout:
View不需要处理,ViewGroup必须实现onLayout来安排子view的位置
onDraw:
View需要实现自己的onDraw就好,ViewGroup通过dispatchDraw以实现对各个子view的绘制
二、自定义view
1、什么是自定义View
使用系统自带的控件重新组合或者继承View、ViewGroup实现特定的效果
2、为什么需要自定义View
现有view不满足需求
3、方式
- 继承于android.view.View或者android.view.ViewGroup
2.继承于android.view.View或者android.view.ViewGroup的相关子类
3.组合View
4、步骤
1.继承android.view.View或者android.view.ViewGroup
2.onLayout
3.onMeasure
4.onDraw
5、例子
public class CustomView extends View {
public CustomView(Context context) {
super(context);
}
public CustomView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width;
int height;
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
if (widthMode == MeasureSpec.EXACTLY) {
width = widthSize;
}
else {
width = widthSize/2;
}
if (heightMode == MeasureSpec.EXACTLY) {
height = heightSize;
}
else {
height = heightSize/2;
}
setMeasuredDimension(width, height);
}
@Override
protected void onDraw(Canvas canvas) {
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
canvas.drawCircle(100, 100, 100, paint);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(20);
canvas.drawCircle(300, 300, 100, paint);
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.FILL);
paint.setTextSize(40);
paint.setColor(Color.RED);
canvas.drawText("我是王贤兵", 200, 200, paint);
paint.setColor(Color.BLUE);
canvas.drawRect(10, 10, 100, 100, paint);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
canvas.drawBitmap(bitmap, 100, 100, paint);
}
}
三、自定义view属性
1、values下新建attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="CustomView">
<attr name="wxb_text_color" format="color" />
<attr name="wxb_stroke_width" format="dimension" />
</declare-styleable>
</resources>
注意format的类型:
(1). reference:参考某一资源ID
(2). color:颜色值
(3). boolean:布尔值
(4). dimension:尺寸值
(5). float:浮点值
(6). integer:整型值
(7). string:字符串
(8). fraction:百分数
(9). enum:枚举值
(10). flag:位或运算
2、获取数据
private void init(AttributeSet attrs) {
if (attrs != null) {
TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.CustomView);
mTextColor = typedArray.getColor(R.styleable.CustomView_wxb_text_color, Color.RED);
mStrokeWidth = typedArray.getDimension(R.styleable.CustomView_wxb_stroke_width, 20);
typedArray.recycle();
}
}
3、例子
public class CustomView extends View {
private float mStrokeWidth = 20;
private int mTextColor = Color.RED;
public CustomView(Context context) {
super(context);
init(null);
}
public CustomView(Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
init(attrs);
}
public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(attrs);
}
public CustomView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(attrs);
}
private void init(AttributeSet attrs) {
if (attrs != null) {
TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.CustomView);
mTextColor = typedArray.getColor(R.styleable.CustomView_wxb_text_color, Color.RED);
mStrokeWidth = typedArray.getDimension(R.styleable.CustomView_wxb_stroke_width, 20);
typedArray.recycle();
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width;
int height;
int widthMode = MeasureSpec.getMode(widthMeasureSpec);
int widthSize = MeasureSpec.getSize(widthMeasureSpec);
int heightMode = MeasureSpec.getMode(heightMeasureSpec);
int heightSize = MeasureSpec.getSize(heightMeasureSpec);
if (widthMode == MeasureSpec.EXACTLY) {
width = widthSize;
}
else {
width = widthSize/2;
}
if (heightMode == MeasureSpec.EXACTLY) {
height = heightSize;
}
else {
height = heightSize/2;
}
setMeasuredDimension(width, height);
}
@Override
protected void onDraw(Canvas canvas) {
Paint paint = new Paint();
paint.setStyle(Paint.Style.FILL);
canvas.drawCircle(100, 100, 100, paint);
paint.setStyle(Paint.Style.STROKE);
paint.setStrokeWidth(mStrokeWidth);
canvas.drawCircle(300, 300, 100, paint);
paint.setColor(Color.RED);
paint.setStyle(Paint.Style.FILL);
paint.setTextSize(40);
paint.setColor(mTextColor);
canvas.drawText("我是王贤兵", 200, 200, paint);
paint.setColor(Color.BLUE);
canvas.drawRect(10, 10, 100, 100, paint);
Bitmap bitmap = BitmapFactory.decodeResource(getResources(), R.drawable.ic_launcher);
canvas.drawBitmap(bitmap, 100, 100, paint);
}
}
四、例子
环形进度条
public void start() {
ValueAnimator valueAnimator = ValueAnimator.ofInt(0, 360);
valueAnimator.setDuration(2000);
valueAnimator.setInterpolator(new LinearInterpolator());
valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
int v = (int)animation.getAnimatedValue();
Log.i("Simon", "onAnimationUpdate v:" + v);
mCurrentValue = v;
invalidate();//强制更新-通知系统刷新本view
}
});
valueAnimator.start();
}
private Paint mCirclePaint = new Paint();
private Paint mTextPaint = new Paint();
private Paint mArcPaint = new Paint();
private float ringSize = 24;//环的宽度
private int mCurrentValue = 0;
@Override
protected void onDraw(Canvas canvas) {
int centre = getWidth() / 2;
int radius = (int) (centre - ringSize/2);
mCirclePaint.setColor(Color.BLACK);//颜色
mCirclePaint.setStyle(Paint.Style.STROKE);//描边
mCirclePaint.setStrokeWidth(ringSize);//环的宽度
mCirclePaint.setAntiAlias(true);//抗锯齿
canvas.drawCircle(centre, centre, radius, mCirclePaint);//画的操作
mArcPaint.setColor(Color.BLUE);
mArcPaint.setStyle(Paint.Style.STROKE);
mArcPaint.setStrokeWidth(ringSize);
RectF rectF = new RectF(centre-radius, centre - radius, centre + radius, centre + radius);
canvas.drawArc(rectF, 90, mCurrentValue, false, mArcPaint);
Log.i("Simon", "onDraw v:" + mCurrentValue);
mCurrentValue = mCurrentValue % 360;
int v = mCurrentValue * 100 / 360;//百分比
String text = v + "%";
float strWidth = mTextPaint.measureText(text);//获取文字长度
mTextPaint.setColor(Color.BLUE);
mTextPaint.setTextSize(80);
canvas.drawText(text, centre - strWidth / 2, centre, mTextPaint);//文字居中
}
滚动歌词
private List<String> mList = new ArrayList<>();//歌词
private Paint mTextPaint = new Paint();//歌词画笔
private int mCurrent;//第一句歌词在屏幕上的y坐标
private int mTotalHeight = 0;//歌词总的高度
private int mTextHeight;//文字高度
private Handler mHandler = new Handler();//用于页面更新
public void start(List<String> list) {
if (list != null) {
mList.addAll(list);
if (mTextPaint != null) {
Rect rect = new Rect();
for (String str : mList) {
mTextPaint.getTextBounds(str, 0, str.length() - 1, rect);
mTotalHeight += rect.height();
mTextHeight = rect.height();
}
}
mCurrent = getHeight();
mHandler.postDelayed(mRunnable, 500);
}
}
private Runnable mRunnable = new Runnable() {
@Override
public void run() {
mHandler.postDelayed(mRunnable, 1000);
mCurrent = mCurrent - 200;
Log.i("Simon", "" + mCurrent);
if (mCurrent < 0) {
int tmp = -mCurrent;
if (tmp > mTotalHeight) {
mCurrent = getHeight();
}
}
invalidate();
}
};
@Override
protected void onDraw(Canvas canvas) {
for (int i = 0; i < mList.size(); i++) {
canvas.drawText(mList.get(i), 0, mCurrent + i * mTextHeight, mTextPaint);
}
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width;
int height;
int widthMode = MeasureSpec.getMode(widthMeasureSpec); //宽度的测量模式
int widthSize = MeasureSpec.getSize(widthMeasureSpec); //宽度的测量值
int heightMode = MeasureSpec.getMode(heightMeasureSpec); //高度的测量模式
int heightSize = MeasureSpec.getSize(heightMeasureSpec); //高度的测量值
//如果布局里面设置的是固定值,这里取布局里面的固定值;如果设置的是match_parent,则取父布局的大小
if (widthMode == MeasureSpec.EXACTLY) {
width = widthSize;
} else {
//如果布局里面没有设置固定值,这里取布局的宽度的1/2
width = widthSize * 1 / 2;
}
if (heightMode == MeasureSpec.EXACTLY) {
height = heightSize;
} else {
//如果布局里面没有设置固定值,这里取布局的高度的3/4
height = heightSize * 1 / 2;
}
setMeasuredDimension(width, height);
}
多TextView排列
public class CustomViewGroupActivity extends AppCompatActivity {
private CustomViewGroup mCustomViewGroup;
private String[] mStrArr = new String[] {
"我是中国人,我是中国人,我是中国人,我是中国人,我是中国人,我是中国人,我是中国人",
"赵铅酸",
"我是中国人,我是中国人,我是中国人,我是中国人,我是中国人,我是中国人,我是中国人",
"哈哈",
"呵呵",
"洗洗",
"流苏",
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_custom_view_group);
mCustomViewGroup = findViewById(R.id.custom_view_group);
findViewById(R.id.button).setOnClickListener(v -> {
// mCustomViewGroup
for (int i = 0; i < mStrArr.length; i++) {
TextView tv = new TextView(this);
tv.setText(mStrArr[i]);
tv.setBackgroundColor(Color.RED);
mCustomViewGroup.addView(tv);
}
mCustomViewGroup.requestLayout();
// mCustomViewGroup.invalidate();
});
}
}
import android.content.Context;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup;
public class CustomViewGroup extends ViewGroup {
private int padding = 10;
private int margin = 10;
public CustomViewGroup(Context context) {
super(context);
}
public CustomViewGroup(Context context, AttributeSet attrs) {
super(context, attrs);
}
public CustomViewGroup(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
public CustomViewGroup(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int width = MeasureSpec.getSize(widthMeasureSpec);
int currentX = 0;
int currentY = 0;
int row = 1;
int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
child.setPadding(padding, padding, padding, padding);
child.measure(MeasureSpec.UNSPECIFIED, MeasureSpec.UNSPECIFIED);
int measureWidth = child.getMeasuredWidth();
int measureHeight = child.getMeasuredHeight();
currentX = currentX +measureWidth + margin;
if (currentX > width - margin) {
if (i != 0) {
row ++;
currentX = measureWidth + margin;
}
}
currentY = row * (measureHeight + margin);
}
setMeasuredDimension(width, currentY + margin);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
int width = r - l;
int currentX = 0;
int currentY = 0;
int row = 1;
int childCount = getChildCount();
for (int i = 0; i < childCount; i++) {
View child = getChildAt(i);
int measureWidth = child.getMeasuredWidth();
int measureHeight = child.getMeasuredHeight();
currentX = currentX +measureWidth + margin;
if (currentX > width - margin) {
if (i != 0) {
row ++;
currentX = measureWidth + margin;
}
}
if (currentX > width - margin) {
currentX = width - margin;
measureWidth = width - margin * 2;
}
currentY = row * (measureHeight + margin);
child.layout(currentX - measureWidth, currentY - measureHeight, currentX, currentY);
}
}
}
五、事件分发
1、分发对象
MotionEvent
2、事件
MotionEvent.ACTION_DOWN
MotionEvent.ACTION_UP
MotionEvent.ACTION_MOVE
MotionEvent.ACTION_CANCEL
3、顺序
Activity->ViewGroup->View
4、重要方法
dispatchTouchEvent (MotionEvent event)进行事件分发。
onlnterceptTouchEvent(MotionEvent event)用来进行事件拦截 只有ViewGroup有
onTouchEvent(MothionEvent event);用来处理事件。
5、流程
a. 对于 dispatchTouchEvent,onTouchEvent,return true是终结事件传递。return false 是回溯到父View的onTouchEvent方法。
b. ViewGroup 想把自己分发给自己的onTouchEvent,需要拦截器onInterceptTouchEvent方法return true 把事件拦截下来。
c. ViewGroup 的拦截器onInterceptTouchEvent 默认是不拦截的,所以return super.onInterceptTouchEvent()=return false;
d. View 没有拦截器,为了让View可以把事件分发给自己的onTouchEvent,View的dispatchTouchEvent默认实现(super)就是把事件分发给自己的onTouchEvent。
6、View和ViewGroup事件分发的区别
- View不包含onInterceptTouchEvent方法,事件到了View这里要么处理要么不处理
- ViewGroup包含onInterceptTouchEvent方法