基本知识
1、我们在自定义视图View的时候正确的步骤和方法
1)、必须定义有Context/Attrbuite参数的构造方法,并且调用父类的方法
public LabelView(Context context, AttributeSet attrs)
否则会出现bug:
2) 当定义宽高属性为wrap_content时,必须onMeasure()来设置view大小.
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
setMeasuredDimension(measureWidth(widthMeasureSpec),
measureHeight(heightMeasureSpec));
}
private int measureWidth(int measureSpec) {
int result = 0;
int specMode = MeasureSpec.getMode(measureSpec);
int specSize = MeasureSpec.getSize(measureSpec);
if (specMode == MeasureSpec.EXACTLY) {
// We were told how big to be
result = specSize;
} else {
// Measure the text
result = (int) mTextPaint.measureText(mText) + getPaddingLeft() + getPaddingRight();
if (specMode == MeasureSpec.AT_MOST) {
// Respect AT_MOST value if that was what is called for by measureSpec
result = Math.min(result, specSize);
}
}
return result;
}
3)、重写onTouchEvent方法
获取坐标,计算坐标,然后通过invalidate和postInvalidate方法进行画面的刷新操作即可
关于这两个刷新方法的区别是:invalidate方法是在UI线程中调用的,postInvalidate可以在子线程中调用,而且最重要的是postInvalidate可以延迟调用
例子
第一个例子:自定义LabelView
这个View主要实现的功能和Android中提供的TextView差不多