理解MeasureSpec

MesaureSpec は View の内部クラスです。ビューの仕様サイズをカプセル化します。ビューの幅と高さの情報が含まれます。その機能は、Measure のプロセス中に、システムが親コンテナによって課されたルールに従って View の LayoutParams を対応する MeasureSpec に変換し、onMeasure の MeasureSpec に従って View の幅と高さを決定することです。方法。

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
         */
        @UnsupportedAppUsage
        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 の定数から、それが 32 ビットの int 値を表し、上位 2 ビットが specMode を表し、下位 30 ビットが specSize を表すことがわかります。specMode は測定モードを指し、specSize は測定サイズを指します。

specMode には次の 3 つのモードがあります。

UNSPECIFIED: モードは指定されておらず、ビューは必要なだけ大きくできます。親コンテナには制限がありません。通常、システムの内部測定に使用されます。

AT_MOST: 最大モード。wrap_content 属性に対応します。子ビューの最終サイズは、親ビューで指定された specSize 値であり、子ビューのサイズはこの値を超えることはできません。

EXACTLY: 正確モード。match_parent 属性と特定の値に応じて、親コンテナはビューに必要なサイズ (specSize の値) を測定します。

ビューごとに MeasureSpec が保持され、MeasureSpec はビューのサイズ仕様を保存します。View の計測処理では、makeMeasureSpec を通じて幅と高さの情報を保存します。getMode または getSize を通じてモード、幅、高さを取得します。MesaureSpec は、独自の LayoutParams と親コンテナの MeasureSpect の影響を受けます。トップレベルの View としての DecorView には親コンテナがありません。では、どのようにして MeasureSpec を取得するのでしょうか? ViewRootImpl の PerformTraversals メソッドを振り返ってみましょう。

private void performTraversals(){
	...
    if(!mStopped){
		int childWidthMeasureSpec = getRootMeasureSpec(mWidth,lp.width);
		int childHeightMeasureSpec = getRootMeasureSpec(mHeight,lp.height);
		performLayout(lp,desiredWindowWidth,desiredWindowHeight);
    }
}

   if(didLayout) {
	 performLayout(lp,desiredWindowWidth,desiredWindowHeight);
	 ..
   }
   if(!cancelDraw && !newSureface) {
		if(!skipDraw || mReportNextDraw) {
			if(mPendingTransition != null && mPendingTransitions.size > 0) {
				for(int i=0; i< mPendingTransitions.size;++i) {
					mPendingTransitions.get(i).startChangingAimations();
				}
				mPendingTransitions.clear();
			}
			performDraw();
		}
   }
   ...
}

この文を見てください。

int childWidthMeasureSpec = getRootMeasureSpec(mWidth,lp.width);

ここで getRootMearueSpec メソッドが呼び出されます。このメソッドが何を行うかを調べてみましょう。

 private static int getRootMeasureSpec(int windowSize, int rootDimension) {
        int measureSpec;
        switch (rootDimension) {

        case ViewGroup.LayoutParams.MATCH_PARENT:
            // Window can't resize. Force root view to be windowSize.
            measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.EXACTLY);
            break;
        case ViewGroup.LayoutParams.WRAP_CONTENT:
            // Window can resize. Set max size for root view.
            measureSpec = MeasureSpec.makeMeasureSpec(windowSize, MeasureSpec.AT_MOST);
            break;
        default:
            // Window wants to be an exact size. Force root view to be that size.
            measureSpec = MeasureSpec.makeMeasureSpec(rootDimension, MeasureSpec.EXACTLY);
            break;
        }
        return measureSpec;
    }

最初のパラメータ windowSize はウィンドウのサイズを指します。そのため、DecorView の MeasureSpec は、独自の LayoutParams とウィンドウのサイズによって決まります。通常のビューとは異なります。通常のビューがどのように決定されるかを覚えていますか? 通常のビューは、独自の LayoutParams と親コンテナの MeasureSpec によって決定されます。次に、次のコードを見ると、DecorView が独自のlayoutParams に従って異なる MeasureSpecs を取得していることがわかります。したがって、前に説明した PerformMeasure メソッドは、chid の MesaureSpec の幅と高さを表す 2 つのパラメータ、つまり childWidthMeasureSpec と childHeightMeasureSpec を渡す必要があります。次に、performTraversals メソッドに戻り、perfromMeasure メソッド内で何が行われるかを確認します。

private void performMeasure(int childWidthMeasureSpec, int childHeightMeasureSpec) {
        if (mView == null) {
            return;
        }
        Trace.traceBegin(Trace.TRACE_TAG_VIEW, "measure");
        try {
            mView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
        } finally {
            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
        }
    }

ここでは、View の測定メソッドが呼び出されていることが明確にわかります。

おすすめ

転載: blog.csdn.net/howlaa/article/details/128621322
おすすめ