自定义View(风度翩翩)

2020-01-16 09:04栏目:龙竞技官网
TAG:

2、自定义View要点

  1. View须要协理wrap_content
  2. View供给帮助padding
  3. 用尽了全力不要再View中使用Handler,View已经有post种类方法
  4. View假如有线程大概动漫片,必要立刻止住(onDetachedFromWindow会在View被remove时调用卡塔尔国——制止内部存款和储蓄器走漏
  5. View如若有滑动嵌套情况,须要管理好滑动冲突
让View支持wrap_content

因此不扶助wrap_content属性,是因为大家的自定义View未有重写onMeasure(State of Qatar方法,View暗中同意的onMeasure()方法只援救EXACTLY情势,所以能够钦赐控件的具体宽高值可能match_parent属性,要是要自定义的view帮衬wrap_content属性,就必需重写onMeasure()方法。
步入代码如下:

 @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
      //  super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(measureWidth(widthMeasureSpec),measureHeight(heightMeasureSpec));
    }


    /**
     * 获得测量的宽度
     * @param widthMeasureSpec
     * @return
     */
    private int measureWidth(int widthMeasureSpec){
        int width = 0;
        int mode=MeasureSpec.getMode(widthMeasureSpec); //获得测量模式
        int size=MeasureSpec.getSize(widthMeasureSpec); //获得测量值
        if (mode==MeasureSpec.EXACTLY){ //精准测量模式
            width=size;
        }else {
            width=300;
            if (mode==MeasureSpec.AT_MOST){
                width=Math.min(width,size);
            }
        }
        return  width;
    }


    /**
     * 获得测量的高度
     * @param heightMeasureSpec
     * @return
     */
    private int measureHeight(int heightMeasureSpec){
        int height = 0;
        int mode=MeasureSpec.getMode(heightMeasureSpec); //获得测量模式
        int size=MeasureSpec.getSize(heightMeasureSpec); //获得测量值
        if (mode==MeasureSpec.EXACTLY){ //精准测量模式
            height=size;
        }else {
            height=300;
            if (mode==MeasureSpec.AT_MOST){
                height=Math.min(width,size);
            }
        }
        return  height;
    }

图片 1

能够看到,重写onMeasure(卡塔尔方法后,VIew已经扶持wrap_content了。

二、自定义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带有滑动嵌套境况时,供给管理好滑动矛盾

图片 2ED9EF9312D01ADABDFADF481CF32A26C.jpg

下边就用代码展示下自定义View的主导步骤:
  • 新建BasicCustomView继承View
    全体代码如下
public class BasicCustomView extends View {

    private Paint mPaint;

    public BasicCustomView(Context context) {
        super(context);
        initView();
    }

    public BasicCustomView(Context context, AttributeSet attrs) {
        super(context, attrs);
        initView();
    }

    public BasicCustomView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initView();
    }

    private void initView() {
        mPaint = new Paint();
        mPaint.setColor(Color.RED);
        mPaint.setStyle(Paint.Style.FILL);
    }

    @Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int width = getWidth();
        int height = getHeight();
       canvas.translate(width/2,height/2);
        canvas.drawCircle(0,0,100,mPaint);
    }
}

第意气风发验证自定义View是或不是扶持layout_margin,padding,wrap_content等属性,验证代码如下:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_custom_view_basic"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    tools:context="com.example.ahuang.viewandgroup.activity.CustomViewBasicActivity">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">
        <com.example.ahuang.viewandgroup.View.BasicCustomView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:layout_margin="20dp"
            android:background="#111fff"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">
        <com.example.ahuang.viewandgroup.View.BasicCustomView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:background="#111fff"/>
    </LinearLayout>
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="0dp"
        android:layout_weight="1">
        <com.example.ahuang.viewandgroup.View.BasicCustomView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="#111fff"
            android:padding="20dp"/>
    </LinearLayout>

</LinearLayout>

图片 3

上海教室申明图大家的自定义View
1.支持layout_margin属性
2.不支持padding属性
3.证实不补助wrap_content

透过后面包车型地铁《View的风云体系》以至《View的干活原理》,对于自定义View已经有了比较足够的摸底,接下去就足以对前边Android View的风云体系(三)——滑动矛盾里头的HorizontalScrollViewEx那么些自定义View做贰个越来越的接头了。
以前,依旧先记下一下局地理论知识吧。

废话少说,先上海教室

自定义View的注意事项
  • 让View支持wrap_content
    那是因为意气风发间接轨View或ViewGroup的控件,假若不在onMeasure中拍卖wrap_content,那么外部在构造中应用wrap_content时就不能够达到预期效果
  • 让View支持padding
    风流倜傥直接轨View的控件,倘使不再draw方法中管理padding,那么那几个本性是力所比不上起功能的。间接接轨ViewGroup的控件须求在onMeasure和onLayout初级中学结业生升学考试虑padding和子成分的margin对其形成的震慑,不然将引致pading和子元素的margin失效
  • 不要在View中使用Handler
    那是因为View内部自个儿就提供了post体系方法,完全能够庖代Handler的功能。除非您很明显要用Handler来发送音信。
  • View中只要有线程和动漫,及时止住
    借使有线程和动漫片必要截止的时候,onDetachedFromWindow就恶意做到。那是因为当包涵此View的Activity退出也许当前View被remove时,View的onDetachedFromWindow方法就能被调用。相没错,当富含此View的Activity运营时onAttachedToWindow会被调用。同一时候,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(State of Qatar,而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);
    }
}

版权声明:本文由龙竞技官网发布于龙竞技官网,转载请注明出处:自定义View(风度翩翩)