Android 自定义View

通过前面的《View的事件体系》以及《View的工作原理》,对于自定义View已经有了比较充分的了解,接下来就可以对之前Android View的事件体系(三)——滑动冲突里面的HorizontalScrollViewEx这个自定义View做一个进一步的理解了。
在此之前,还是先记录一下一些理论知识吧。

一、自定义View的分类

  • 1、继承View重写onDraw方法
    这种方法主要用于实现一些不规则的效果,用自己的方式来绘制出一些不规则的图形。采用这种方式需要自己支持wrap_content和padding。
  • 2、集成ViewGroup派生特殊的Layout
    这种方法主要用于实现自定义的布局,即重新定义一种有别于LinearLayout,RelativeLayout等的新布局。采用这种方式需要合适地处理ViewGroup的测量、布局这两个过程,并同时处理子元素的测量和布局过程。
  • 3、继承特定的View(比如TextView)
    这种方法一般用于扩展某种已有的View的功能,不需要自己支持wrap_content和padding等。
  • 4、继承特定的ViewGroup(比如LinearLayout)
    采用这种方法不需要自己处理ViewGroup的测量和布局这两个过程,一般来说方法2能实现的效果方法4也都能实现,两者的区别在于方法2更接近View的底层。

二、自定义View须知

  • 1、让View支持wrap_content
    直接继承View或者ViewGroup的控件,如果不再onMeasure中对wrap_content做特殊处理,则当控件使用wrap_content时就无法达到预期的效果,具体原因在Android View的工作原理中的View的measure过程有介绍过。
  • 2、如果有必要,让自定义View支持padding
    直接继承View的控件,如果不再draw方法中处理padding的话,padding属性是无法起作用的。直接继承ViewGroup的控件需要在onMeasure和onLayout中考虑padding和子元素margin对其造成的影响,不然同样会使padding与子元素的margin失效。
  • 3、尽量不要在View中使用Handler,没必要
    View内部本身提供了post系列的方法,完全可以替代Handler的作用。
  • 4、View带有滑动嵌套情形时,需要处理好滑动冲突

三、自定义View示例

  • 1、继承View重写onDraw方法

这里选择实现一个绘制一个圆的自定义控件,在实现过程中必须考虑到wrap_content模式以及padding,同时为了提高便捷性,还要对外提供自定义属性。

第一步,在values目录下创建自定义属性的attrs.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="CircleView">
        <attr name="circle_color" format="color"/>
    </declare-styleable>
</resources>

声明了一个自定义属性集合“CircleView”,这个集合里面可以有很多自定义的属性,格式可以是颜色格式:color、资源格式:reference、尺寸格式:dimension等,这里只定义了一个颜色格式的属性“circle_color”。

第二步,在View的构造方法中解析自定义属性的值并做相应处理:

    public CircleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        // 首先加载自定义属性集合CircleView
        TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.CircleView);
        // 接着解析CircleView属性集合中的circle_color,如果在使用时没有指定circle这个属性
        // 就选择红色作为默认颜色
        mColor = a.getColor(R.styleable.CircleView_circle_color,Color.RED);
        // 解析完后用recycle方法释放资源
        a.recycle();
        init();
    }

第三步,在CircleView的onMeasure中处理wrap_content模式,设置一个默认的大小:

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);

        // 处理wrap_content
        if(widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST){
            setMeasuredDimension(200,200);
        } else if (widthSpecMode == MeasureSpec.AT_MOST){
            setMeasuredDimension(200,heightSpecSize);
        } else if (heightSpecMode == MeasureSpec.AT_MOST){
            setMeasuredDimension(widthSpecSize,200);
        }
    }

第四步,在onDraw中处理padding,并画出图形:

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int paddingLeft = getPaddingLeft();
        int paddingRight = getPaddingRight();
        int paddingTop = getPaddingTop();
        int paddingBottom = getPaddingBottom();
        // 处理padding
        int width = getWidth() - paddingLeft - paddingRight;
        int height = getHeight() - paddingTop - paddingBottom;
        int radius = Math.min(width,height) /2;
        canvas.drawCircle(paddingLeft + width / 2,paddingTop + height /2,radius,mPaint);
    }

第五步,在布局中使用自定义View:

    <com.example.freezing.rxjava2demo.CircleView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@android:color/holo_blue_bright"
        app:circle_color="@android:color/holo_green_dark"
        android:padding="10dp"
        />

这样一个自定义View就完成了,以下是完整的代码:

public class CircleView extends View {

    private int mColor = Color.RED;
    private Paint mPaint = new Paint(Paint.ANTI_ALIAS_FLAG);

    /**
     * 第一个构造函数
     * @param context
     */
    public CircleView(Context context) {
        super(context);
        init();
    }

    /**
     * 第二个构造函数
     * @param context
     * @param attrs
     */
    public CircleView(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs,0);
    }

    /**
     * 第三个构造函数
     * @param context
     * @param attrs
     * @param defStyleAttr
     */
    public CircleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.CircleView);
        mColor = a.getColor(R.styleable.CircleView_circle_color,Color.RED);
        a.recycle();
        init();
    }

    private void init(){
        mPaint.setColor(mColor);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSpecSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSpecSize = MeasureSpec.getSize(heightMeasureSpec);

        // 处理wrap_content
        if(widthSpecMode == MeasureSpec.AT_MOST && heightSpecMode == MeasureSpec.AT_MOST){
            setMeasuredDimension(200,200);
        } else if (widthSpecMode == MeasureSpec.AT_MOST){
            setMeasuredDimension(200,heightSpecSize);
        } else if (heightSpecMode == MeasureSpec.AT_MOST){
            setMeasuredDimension(widthSpecSize,200);
        }
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int paddingLeft = getPaddingLeft();
        int paddingRight = getPaddingRight();
        int paddingTop = getPaddingTop();
        int paddingBottom = getPaddingBottom();
        // 处理padding
        int width = getWidth() - paddingLeft - paddingRight;
        int height = getHeight() - paddingTop - paddingBottom;
        int radius = Math.min(width,height) /2;
        canvas.drawCircle(paddingLeft + width / 2,paddingTop + height /2,radius,mPaint);
    }
}

这里还有一点需要了解的是自定义View的构造函数:

  • 1、在代码中直接new一个CircleView实例的时候,会调用第一个构造函数;
  • 2、在xml布局文件中调用CircleView的时候,会调用第二个构造函数;
  • 3、在xml布局文件中调用CircleView,并且CircleView标签中还有自定义属性时,这里调用的还是第二个构造函数。

也就是说,系统默认只会调用CircleView的前两个构造函数,至于第三个构造函数的调用,通常是我们自己在构造函数中主动调用的(例如,在第二个构造函数中调用第三个构造函数)

  • 2、继承ViewGroup派生特殊的Layout
    之前的HorizontalScrollViewEx就是通过集成ViewGroup来实现的。
    HorizontalScrollViewEx的功能主要是类似于ViewPager的控件,其内部的子元素可以进行水平滑动并且子元素的内部还可以进行竖直滑动,在之前的文章里只是说明了如何解决滑动冲突的内容,这里可以进一步了解它的measure和layout过程。这里的代码有别于之前的代码,因为我重新处理了它的wrap_content,padding以及子元素的margin问题,先看onMeasure:
    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int measuredWidth = 0;
        int measuredHeight = 0;
        mChildMarginLeft = 0;
        mChildMarginTop = 0;
        mChildMarginRight = 0;
        mChildMarginBottom = 0;
        mViewGroupPaddingLeft = getPaddingLeft();
        mViewGroupPaddingTop = getPaddingTop();
        mViewGroupPaddingRight = getPaddingRight();
        mViewGroupPaddingBottom = getPaddingBottom();
        final int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View childView = getChildAt(i);
            MarginLayoutParams lp = (MarginLayoutParams) childView.getLayoutParams();
            measureChildWithMargins(childView,widthMeasureSpec,0,heightMeasureSpec,0);
            measuredWidth += childView.getMeasuredWidth(); // 计算所有子元素的宽度和
            measuredHeight = Math.max(measuredHeight,childView.getMeasuredHeight());// 计算所有子元素中的最大的高度
            mChildMarginLeft += lp.leftMargin; // 计算所有子元素的左边距和
            mChildMarginTop = Math.max(mChildMarginTop,lp.topMargin); // 计算所有子元素中的最大上边距
            mChildMarginRight += lp.rightMargin; // 计算所有子元素的右边距和
            mChildMarginBottom = Math.max(mChildMarginBottom,lp.bottomMargin);// 计算所有子元素中的最大下边距
        }
        // 用于处理wrap_content的情况
        mViewGroupWidth = measuredWidth + mChildMarginLeft + mChildMarginRight + mViewGroupPaddingLeft + mViewGroupPaddingRight;
        mViewGroupHeight = measuredHeight + mChildMarginTop + mChildMarginBottom + mViewGroupPaddingTop + mViewGroupPaddingBottom;

        setMeasuredDimension(measureWidth(widthMeasureSpec,mViewGroupWidth),measureHeight(heightMeasureSpec,mViewGroupHeight));
    }

    private int measureWidth(int widthMeasureSpec, int viewGroupWidth){
        int measureWidth = 0;
        int widthSpaceSize = MeasureSpec.getSize(widthMeasureSpec);
        int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
        switch (widthSpecMode) {
            case MeasureSpec.UNSPECIFIED:
                measureWidth = widthSpaceSize;
                break;
            case MeasureSpec.AT_MOST:
                // 将剩余宽度与自身padding+所有子元素的宽度+子元素margin的值对比,取最小的作为宽度
                measureWidth = Math.min(viewGroupWidth,widthSpaceSize);
                break;
            case MeasureSpec.EXACTLY:
                measureWidth = widthSpaceSize;
                break;
        }

        return measureWidth;
    }

    private int measureHeight(int heightMeasureSpec, int viewGroupHeight){
        int measureHeight = 0;
        int heightSpaceSize = MeasureSpec.getSize(heightMeasureSpec);
        int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
        switch (heightSpecMode) {
            case MeasureSpec.UNSPECIFIED:
                measureHeight = heightSpaceSize;
                break;
            case MeasureSpec.AT_MOST:
                // 将剩余宽度与自身padding+所有子元素的宽度+子元素margin的值对比,取最小的作为宽度
                measureHeight = Math.min(viewGroupHeight,heightSpaceSize);
                break;
            case MeasureSpec.EXACTLY:
                measureHeight = heightSpaceSize;
                break;
        }

        return measureHeight;
    }

这里说明一下上述代码的逻辑,首先先对所有子元素进行测量,包括子元素的margin也要一并测量,然后计算出所有子元素的宽度和(包括所有子元素本身宽度及其左右的margin和父布局的左右padding)和高度(所有子元素中最大高度以及各子元素的上下margin和父布局的上下padding),这两个值主要是用来作为当宽/高采用了wrap_content时的宽/高值。

再看onLayout方法:

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        // 子元素初始左坐标为父布局的paddingLeft值
        int childLeft = getPaddingLeft();
        final int childCount = getChildCount();
        mChildSize = childCount;

        for (int i = 0; i < childCount; i++) {
            final View childView = getChildAt(i);
            if(childView.getVisibility() != View.GONE){
                // 子元素本身宽度
                final int childWidth = childView.getMeasuredWidth();
                MarginLayoutParams lp = (MarginLayoutParams) childView.getLayoutParams();
                // 子元素距离顶部的距离为父布局的paddingTop + 子元素的marginTop
                int childTop = getPaddingTop() + lp.topMargin;
                // 子元素占用父布局的总宽度
                mChildWidth = childWidth + lp.leftMargin + lp.rightMargin;
                // 子元素距离左边的距离为父布局的paddingLeft + 子元素的marginLeft
                childLeft += lp.leftMargin;
                // 对子元素进行定位
                childView.layout(childLeft,childTop,childLeft + childWidth,childTop + childView.getMeasuredHeight());
                // 计算下一个子元素的初始左坐标
                childLeft += childWidth + lp.rightMargin;
            }
        }
    }

    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new MarginLayoutParams(getContext(),attrs);
    }

这里的作用是完成子元素的定位,首先遍历所有子元素,如果子元素不是处于GONE状态,就通过layout方法将其放在合适的位置。这里的放置过程是从左到右的。值得注意的是,这里还需要添加多一个generateLayoutParams方法,否则的话将会报强制类型转换的错误:
java.lang.ClassCastException: android.view.ViewGroup$LayoutParams cannot be cast to android.view.ViewGroup$MarginLayoutParams
原因是在onMeasure里面使用了childView.getLayoutParams(),而ViewGroup默认返回的值的类型是LayoutParams,它不能为强制类型转换成MarginLayoutParams,所以需要重写generateLayoutParams来重置它的LayoutParams类型为MarginLayoutParams。

下面附上修改后的HorizontalScrollViewEx源码:

public class HorizontalScrollViewEx extends ViewGroup {

    private static final String TAG = "HorizontalScrollViewEx";

    private int mChildSize;
    private int mChildWidth;
    private int mChildIndex;
    private int mChildMarginLeft;
    private int mChildMarginTop;
    private int mChildMarginRight;
    private int mChildMarginBottom;

    private int mViewGroupWidth;
    private int mViewGroupHeight;
    private int mViewGroupPaddingLeft;
    private int mViewGroupPaddingTop;
    private int mViewGroupPaddingRight;
    private int mViewGroupPaddingBottom;

    // 记录上次滑动的坐标
    private int mLastX = 0;
    private int mLastY = 0;

    // 记录上次滑动的坐标(onInterceptTouchEvent)
    private int mLastXIntercept = 0;
    private int mLastYIntercept = 0;

    private Scroller mScroller;
    private VelocityTracker mVelocityTracker;

    public HorizontalScrollViewEx(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        init();
    }

    public HorizontalScrollViewEx(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    public HorizontalScrollViewEx(Context context) {
        super(context);
        init();
    }

    private void init() {
        if (mScroller == null) {
            mScroller = new Scroller(getContext());
            mVelocityTracker = VelocityTracker.obtain();
        }
    }

    @Override
    public boolean onInterceptTouchEvent(MotionEvent ev) {
        boolean intercepted = false;
        int x = (int) ev.getX();
        int y = (int) ev.getY();

        switch (ev.getAction()) {
            case MotionEvent.ACTION_DOWN:
                intercepted = false;
                // 优化滑动用户体验,非必须
                if (!mScroller.isFinished()) {
                    mScroller.abortAnimation();
                    intercepted = true;
                }
                break;
            case MotionEvent.ACTION_MOVE:
                int deltaX = x - mLastXIntercept;
                int deltaY = y - mLastYIntercept;
                // 判断是横向滑动还是纵向滑动
                if (Math.abs(deltaX) > Math.abs(deltaY)) {
                    intercepted = true;
                } else {
                    intercepted = false;
                }
                break;
            case MotionEvent.ACTION_UP:
                intercepted = false;
                break;
            default:

                break;
        }
        mLastX = x;
        mLastY = y;
        mLastXIntercept = x;
        mLastYIntercept = y;
        return intercepted;
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        mVelocityTracker.addMovement(event);
        int x = (int) event.getX();
        int y = (int) event.getY();
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                if (!mScroller.isFinished()) {
                    mScroller.abortAnimation();
                }
                break;
            case MotionEvent.ACTION_MOVE:
                int deltaX = x - mLastX;
                scrollBy(-deltaX,0);
                break;
            case MotionEvent.ACTION_UP:
                int scrollX = getScrollX();
                mVelocityTracker.computeCurrentVelocity(1000);
                float xVelocity = mVelocityTracker.getXVelocity();
                if(Math.abs(xVelocity) > 50){
                    mChildIndex = xVelocity > 0 ? mChildIndex - 1: mChildIndex + 1;
                } else {
                    mChildIndex = (scrollX + mChildWidth /2)/ mChildWidth;
                }
                mChildIndex = Math.max(0,Math.min(mChildIndex, mChildSize - 1));
                int dx = mChildIndex * mChildWidth - scrollX;
                smoothScrollBy(dx,0);
                mVelocityTracker.clear();
                break;
            default:

                break;
        }

        mLastX = x;
        mLastY = y;
        return true;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        int measuredWidth = 0;
        int measuredHeight = 0;
        mChildMarginLeft = 0;
        mChildMarginTop = 0;
        mChildMarginRight = 0;
        mChildMarginBottom = 0;
        mViewGroupPaddingLeft = getPaddingLeft();
        mViewGroupPaddingTop = getPaddingTop();
        mViewGroupPaddingRight = getPaddingRight();
        mViewGroupPaddingBottom = getPaddingBottom();
        final int childCount = getChildCount();
        for (int i = 0; i < childCount; i++) {
            View childView = getChildAt(i);
            MarginLayoutParams lp = (MarginLayoutParams) childView.getLayoutParams();
            measureChildWithMargins(childView,widthMeasureSpec,0,heightMeasureSpec,0);
            measuredWidth += childView.getMeasuredWidth(); // 计算所有子元素的宽度和
            measuredHeight = Math.max(measuredHeight,childView.getMeasuredHeight());// 计算所有子元素中的最大的高度
            mChildMarginLeft += lp.leftMargin; // 计算所有子元素的左边距和
            mChildMarginTop = Math.max(mChildMarginTop,lp.topMargin); // 计算所有子元素中的最大上边距
            mChildMarginRight += lp.rightMargin; // 计算所有子元素的右边距和
            mChildMarginBottom = Math.max(mChildMarginBottom,lp.bottomMargin);// 计算所有子元素中的最大下边距

            Log.i(TAG, "onMeasure: 子View的宽:" +  childView.getMeasuredWidth());
            Log.i(TAG, "onMeasure: 子View的高:" + childView.getMeasuredHeight());
        }
        // 用于处理wrap_content的情况
        mViewGroupWidth = measuredWidth + mChildMarginLeft + mChildMarginRight + mViewGroupPaddingLeft + mViewGroupPaddingRight;
        mViewGroupHeight = measuredHeight + mChildMarginTop + mChildMarginBottom + mViewGroupPaddingTop + mViewGroupPaddingBottom;

        setMeasuredDimension(measureWidth(widthMeasureSpec,mViewGroupWidth),measureHeight(heightMeasureSpec,mViewGroupHeight));


        Log.i(TAG, "onMeasure: ViewGroup的宽:" + getMeasuredWidth());
    }

    private int measureWidth(int widthMeasureSpec, int viewGroupWidth){
        int measureWidth = 0;
        int widthSpaceSize = MeasureSpec.getSize(widthMeasureSpec);
        int widthSpecMode = MeasureSpec.getMode(widthMeasureSpec);
        switch (widthSpecMode) {
            case MeasureSpec.UNSPECIFIED:
                measureWidth = widthSpaceSize;
                break;
            case MeasureSpec.AT_MOST:
                // 将剩余宽度与自身padding+所有子元素的宽度+子元素margin的值对比,取最小的作为宽度
                measureWidth = Math.min(viewGroupWidth,widthSpaceSize);
                break;
            case MeasureSpec.EXACTLY:
                measureWidth = widthSpaceSize;
                break;
        }

        return measureWidth;
    }

    private int measureHeight(int heightMeasureSpec, int viewGroupHeight){
        int measureHeight = 0;
        int heightSpaceSize = MeasureSpec.getSize(heightMeasureSpec);
        int heightSpecMode = MeasureSpec.getMode(heightMeasureSpec);
        switch (heightSpecMode) {
            case MeasureSpec.UNSPECIFIED:
                measureHeight = heightSpaceSize;
                break;
            case MeasureSpec.AT_MOST:
                // 将剩余宽度与自身padding+所有子元素的宽度+子元素margin的值对比,取最小的作为宽度
                measureHeight = Math.min(viewGroupHeight,heightSpaceSize);
                break;
            case MeasureSpec.EXACTLY:
                measureHeight = heightSpaceSize;
                break;
        }

        return measureHeight;
    }

    @Override
    protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
        // 子元素初始左坐标为父布局的paddingLeft值
        int childLeft = getPaddingLeft();
        final int childCount = getChildCount();
        mChildSize = childCount;

        for (int i = 0; i < childCount; i++) {
            final View childView = getChildAt(i);
            if(childView.getVisibility() != View.GONE){
                // 子元素本身宽度
                final int childWidth = childView.getMeasuredWidth();
                MarginLayoutParams lp = (MarginLayoutParams) childView.getLayoutParams();
                // 子元素距离顶部的距离为父布局的paddingTop + 子元素的marginTop
                int childTop = getPaddingTop() + lp.topMargin;
                // 子元素占用父布局的总宽度
                mChildWidth = childWidth + lp.leftMargin + lp.rightMargin;
                // 子元素距离左边的距离为父布局的paddingLeft + 子元素的marginLeft
                childLeft += lp.leftMargin;
                // 对子元素进行定位
                childView.layout(childLeft,childTop,childLeft + childWidth,childTop + childView.getMeasuredHeight());
                // 计算下一个子元素的初始左坐标
                childLeft += childWidth + lp.rightMargin;
            }
        }
    }

    private void smoothScrollBy(int dx, int dy){
        mScroller.startScroll(getScrollX(),0,dx,0,500);
        invalidate();
    }

    @Override
    public void computeScroll() {
        if(mScroller.computeScrollOffset()){
            scrollTo(mScroller.getCurrX(),mScroller.getCurrY());
            postInvalidate();
        }
    }

    @Override
    protected void onDetachedFromWindow() {
        mVelocityTracker.recycle();
        super.onDetachedFromWindow();
    }

    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        return new MarginLayoutParams(getContext(),attrs);
    }
}

推荐阅读更多精彩内容