美文网首页
自定义ViewGroup(二)

自定义ViewGroup(二)

作者: cao苗子 | 来源:发表于2019-08-29 13:58 被阅读0次

    根据我们上一次 文章 修改我们的布局

    <?xml version="1.0" encoding="utf-8"?>
    <com.miaozi.myviewgroup.MyViewGroup
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@color/colorPrimary"
        tools:context=".MainActivity">
        <Button
            android:text="第一"
            android:layout_width="match_parent"
            android:layout_height="100dp" />
        <Button
            android:text="第一"
            android:layout_width="200dp"
            android:layout_height="100dp" />
        <Button
            android:text="第一"
            android:layout_width="100dp"
            android:layout_height="100dp" />
        <TextView
            android:text="我的妈妈呀"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content" />
    
    </com.miaozi.myviewgroup.MyViewGroup>
    

    修改的只有:

     android:layout_width="wrap_content"
     android:layout_height="wrap_content"
    

    效果还是没有变化,这是为什么呢?
    下面我们就来分析:
    (1)view的三种设计模式

    1.MeasureSpec.AT_MOST:大小不可超过某数值,如:wrap_content
    2.MeasureSpec.EXACTLY:确切的大小,如:100dp或者march_parent
    3.MeasureSpec.UNSPECIFIED:不对View大小做限制,如:ListView,ScrollView
    

    (2)我们看MeasureSpec的源码

    public static class MeasureSpec {
            private static final int MODE_SHIFT = 30;
            private static final int MODE_MASK  = 0x3 << MODE_SHIFT;
    
            /** @hide */
            @IntDef({UNSPECIFIED, EXACTLY, AT_MOST})
            @Retention(RetentionPolicy.SOURCE)
            public @interface MeasureSpecMode {}
    
            /**
             * Measure specification mode: The parent has not imposed any constraint
             * on the child. It can be whatever size it wants.
             */
            public static final int UNSPECIFIED = 0 << MODE_SHIFT;
    
            /**
             * Measure specification mode: The parent has determined an exact size
             * for the child. The child is going to be given those bounds regardless
             * of how big it wants to be.
             */
            public static final int EXACTLY     = 1 << MODE_SHIFT;
    
            /**
             * Measure specification mode: The child can be as large as it wants up
             * to the specified size.
             */
            public static final int AT_MOST     = 2 << MODE_SHIFT;
    
            /**
             * Creates a measure specification based on the supplied size and mode.
             *
             * The mode must always be one of the following:
             * <ul>
             *  <li>{@link android.view.View.MeasureSpec#UNSPECIFIED}</li>
             *  <li>{@link android.view.View.MeasureSpec#EXACTLY}</li>
             *  <li>{@link android.view.View.MeasureSpec#AT_MOST}</li>
             * </ul>
             *
             * <p><strong>Note:</strong> On API level 17 and lower, makeMeasureSpec's
             * implementation was such that the order of arguments did not matter
             * and overflow in either value could impact the resulting MeasureSpec.
             * {@link android.widget.RelativeLayout} was affected by this bug.
             * Apps targeting API levels greater than 17 will get the fixed, more strict
             * behavior.</p>
             *
             * @param size the size of the measure specification
             * @param mode the mode of the measure specification
             * @return the measure specification based on size and mode
             */
            public static int makeMeasureSpec(@IntRange(from = 0, to = (1 << MeasureSpec.MODE_SHIFT) - 1) int size,
                                              @MeasureSpecMode int mode) {
                if (sUseBrokenMakeMeasureSpec) {
                    return size + mode;
                } else {
                    return (size & ~MODE_MASK) | (mode & MODE_MASK);
                }
            }
    
            /**
             * Like {@link #makeMeasureSpec(int, int)}, but any spec with a mode of UNSPECIFIED
             * will automatically get a size of 0. Older apps expect this.
             *
             * @hide internal use only for compatibility with system widgets and older apps
             */
            public static int makeSafeMeasureSpec(int size, int mode) {
                if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) {
                    return 0;
                }
                return makeMeasureSpec(size, mode);
            }
    
            /**
             * Extracts the mode from the supplied measure specification.
             *
             * @param measureSpec the measure specification to extract the mode from
             * @return {@link android.view.View.MeasureSpec#UNSPECIFIED},
             *         {@link android.view.View.MeasureSpec#AT_MOST} or
             *         {@link android.view.View.MeasureSpec#EXACTLY}
             */
            @MeasureSpecMode
            public static int getMode(int measureSpec) {
                //noinspection ResourceType
                return (measureSpec & MODE_MASK);
            }
    
            /**
             * Extracts the size from the supplied measure specification.
             *
             * @param measureSpec the measure specification to extract the size from
             * @return the size in pixels defined in the supplied measure specification
             */
            public static int getSize(int measureSpec) {
                return (measureSpec & ~MODE_MASK);
            }
    
            static int adjust(int measureSpec, int delta) {
                final int mode = getMode(measureSpec);
                int size = getSize(measureSpec);
                if (mode == UNSPECIFIED) {
                    // No need to adjust size for UNSPECIFIED mode.
                    return makeMeasureSpec(size, UNSPECIFIED);
                }
                size += delta;
                if (size < 0) {
                    Log.e(VIEW_LOG_TAG, "MeasureSpec.adjust: new size would be negative! (" + size +
                            ") spec: " + toString(measureSpec) + " delta: " + delta);
                    size = 0;
                }
                return makeMeasureSpec(size, mode);
            }
    
            /**
             * Returns a String representation of the specified measure
             * specification.
             *
             * @param measureSpec the measure specification to convert to a String
             * @return a String with the following format: "MeasureSpec: MODE SIZE"
             */
            public static String toString(int measureSpec) {
                int mode = getMode(measureSpec);
                int size = getSize(measureSpec);
    
                StringBuilder sb = new StringBuilder("MeasureSpec: ");
    
                if (mode == UNSPECIFIED)
                    sb.append("UNSPECIFIED ");
                else if (mode == EXACTLY)
                    sb.append("EXACTLY ");
                else if (mode == AT_MOST)
                    sb.append("AT_MOST ");
                else
                    sb.append(mode).append(" ");
    
                sb.append(size);
                return sb.toString();
            }
        }
    

    可见MeasureSpec由两个部分组成,一个mode一个size,总共32位,最高两位代码mode,剩下30位代表size。
    主要的方法有三个:
    第一个:设置mode和size

     public static int makeSafeMeasureSpec(int size, int mode) {
                if (sUseZeroUnspecifiedMeasureSpec && mode == UNSPECIFIED) {
                    return 0;
                }
                return makeMeasureSpec(size, mode);
            }
    

    第二个:获取模式

    public static int getSize(int measureSpec) {
                return (measureSpec & ~MODE_MASK);
            }
    
    

    第三个:获取size

    public static int getMode(int measureSpec) {
                //noinspection ResourceType
                return (measureSpec & MODE_MASK);
            }
    

    带着上面的分析我们重新写onMeasure()方法中的代码:

    
        /**
         * 测量宽高
         * @param widthMeasureSpec
         * @param heightMeasureSpec
         */
        @Override
        protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
            //获取宽度的模式
            int widthMode = MeasureSpec.getMode(widthMeasureSpec);
            //获取高度模式
            int heightMode = MeasureSpec.getMode(heightMeasureSpec);
            //获取width的大小
            int widthSize = MeasureSpec.getSize(widthMeasureSpec);
            //获取height的大小
            int heightSize = MeasureSpec.getSize(heightMeasureSpec);
            //最大宽度
            int maxWidth = 0;
            //最大高度
            int maxHeight = 0;
            int childCount = getChildCount();
            for (int i = 0; i < childCount; i++) {
                View childView = getChildAt(i);
                //测量子view的宽高
                measureChild(childView,widthMeasureSpec,heightMeasureSpec);
                MarginLayoutParams lp = (MarginLayoutParams) childView.getLayoutParams();
                if(maxWidth < lp.width){
                    maxWidth = lp.width;
                }
                maxHeight += lp.height;
            }
            //测量自己的宽高
            if(childCount == 0){
                super.onMeasure(widthMeasureSpec,heightMeasureSpec);
            }else if(widthMode == MeasureSpec.AT_MOST && heightMode == MeasureSpec.AT_MOST){
                //宽高都是wrap_content
                setMeasuredDimension(maxWidth,maxHeight);
            }else if(widthMode == MeasureSpec.AT_MOST){
                //只有宽是wrap_content
                setMeasuredDimension(maxWidth,heightSize);
            }else if(heightMode == MeasureSpec.AT_MOST){
                //只有高是wrap_content
                setMeasuredDimension(widthSize,maxHeight);
            }else {
                setMeasuredDimension(widthSize,heightSize);
            }
        }
    
    

    无论你怎么设置都是正确的了。
    注意要复写:

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

    否则会报错的

    相关文章

      网友评论

          本文标题:自定义ViewGroup(二)

          本文链接:https://www.haomeiwen.com/subject/zambectx.html