当 Activity
获得焦点时,Android 框架会要求 Activity
绘制其布局。Android 框架处理绘制过程,但 Activity
必须提供其布局层次结构的根节点。
Android 框架绘制布局的根节点,并测量和绘制布局树。它通过遍历树并渲染与无效区域相交的每个 View
来进行绘制。每个 ViewGroup
负责使用 draw()
方法请求绘制其每个子元素,并且每个 View
负责绘制自身。由于树是按前序遍历的,因此框架会在其子元素之前(换句话说,在后面)绘制父元素,并且它会按照子元素在树中出现的顺序绘制它们。
Android 框架通过两遍过程绘制布局:测量遍和布局遍。框架在 measure(int, int)
中执行测量遍,并对 View
树进行自上而下的遍历。在递归期间,每个 View
将尺寸规范向下推送到树中。在测量遍结束时,每个 View
都会存储其测量值。框架在 layout(int, int, int, int)
中执行第二遍,并且也是自上而下的。在此遍中,每个父元素负责使用在测量遍中计算的大小来定位其所有子元素。
以下各节将更详细地介绍布局过程的两遍。
启动测量遍
当 View
对象的 measure()
方法返回时,请设置其 getMeasuredWidth()
和 getMeasuredHeight()
值,以及所有 View
对象的后代的值。 View
对象的测量宽度和测量高度值必须遵守 View
对象的父元素施加的约束。这有助于确保在测量遍结束时,所有父元素都接受其所有子元素的测量值。
父 View
可能会在其子元素上多次调用 measure()
。例如,父元素可能会使用未指定的尺寸对子元素进行一次测量,以确定其首选尺寸。如果子元素的无约束尺寸之和过大或过小,则父元素可能会再次调用 measure()
,并使用约束子元素尺寸的值。
测量遍使用两个类来传达尺寸。 ViewGroup.LayoutParams
类是 View
对象传达其首选尺寸和位置的方式。基本 ViewGroup.LayoutParams
类描述了 View
的首选宽度和高度。对于每个维度,它可以指定以下内容之一
- 精确尺寸。
MATCH_PARENT
,表示View
的首选尺寸是其父元素的尺寸,减去填充。WRAP_CONTENT
,表示View
的首选尺寸仅足以包含其内容,加上填充。
对于不同的 ViewGroup
子类,存在 ViewGroup.LayoutParams
的子类。例如,RelativeLayout
有自己的 ViewGroup.LayoutParams
子类,其中包括能够水平和垂直居中子 View
对象的功能。
MeasureSpec
对象用于将需求从父元素向下推送到子元素树中。 MeasureSpec
可以处于以下三种模式之一
UNSPECIFIED
:父元素使用此模式来确定子View
的目标尺寸。例如,LinearLayout
可能会以高度设置为UNSPECIFIED
且宽度为EXACTLY
240 的方式调用其子元素的measure()
,以了解在宽度为 240 像素的情况下,子View
需要多高。EXACTLY
:父元素使用此模式对子元素施加精确尺寸。子元素必须使用此尺寸并保证其所有后代都适合此尺寸。AT_MOST
:父元素使用此模式对子元素施加最大尺寸。子元素必须保证其自身及其所有后代都适合此尺寸。
启动布局遍
要启动布局,请调用 requestLayout()
。此方法通常由 View
本身调用,当它认为自己无法再适应其边界时。
实现自定义测量和布局逻辑
如果您想实现自定义测量或布局逻辑,请覆盖实现该逻辑的方法:onMeasure(int, int)
和 onLayout(boolean, int, int, int, int)
。这些方法分别由 measure(int, int)
和 layout(int, int, int, int)
调用。不要尝试覆盖 measure(int, int)
或 layout(int, int, int, int)
方法,这两个方法都是 final
,因此无法覆盖。
以下示例显示了如何在 `SplitLayout` 类(来自 WindowManager 示例应用)中执行此操作。如果 SplitLayout
具有两个或多个子视图,并且显示屏具有折叠,则它会将这两个子视图分别放置在折叠的两侧。以下示例显示了覆盖测量和布局的用例,但对于生产环境,如果您想要此行为,请使用 SlidingPaneLayout
。
Kotlin
/** * An example of split-layout for two views, separated by a display * feature that goes across the window. When both start and end views are * added, it checks whether there are display features that separate the area * in two—such as a fold or hinge—and places them side-by-side or * top-bottom. */ class SplitLayout : FrameLayout { private var windowLayoutInfo: WindowLayoutInfo? = null private var startViewId = 0 private var endViewId = 0 private var lastWidthMeasureSpec: Int = 0 private var lastHeightMeasureSpec: Int = 0 ... fun updateWindowLayout(windowLayoutInfo: WindowLayoutInfo) { this.windowLayoutInfo = windowLayoutInfo requestLayout() } override fun onLayout(changed: Boolean, left: Int, top: Int, right: Int, bottom: Int) { val startView = findStartView() val endView = findEndView() val splitPositions = splitViewPositions(startView, endView) if (startView != null && endView != null && splitPositions != null) { val startPosition = splitPositions[0] val startWidthSpec = MeasureSpec.makeMeasureSpec(startPosition.width(), EXACTLY) val startHeightSpec = MeasureSpec.makeMeasureSpec(startPosition.height(), EXACTLY) startView.measure(startWidthSpec, startHeightSpec) startView.layout( startPosition.left, startPosition.top, startPosition.right, startPosition.bottom ) val endPosition = splitPositions[1] val endWidthSpec = MeasureSpec.makeMeasureSpec(endPosition.width(), EXACTLY) val endHeightSpec = MeasureSpec.makeMeasureSpec(endPosition.height(), EXACTLY) endView.measure(endWidthSpec, endHeightSpec) endView.layout( endPosition.left, endPosition.top, endPosition.right, endPosition.bottom ) } else { super.onLayout(changed, left, top, right, bottom) } } /** * Gets the position of the split for this view. * @return A rect that defines of split, or {@code null} if there is no split. */ private fun splitViewPositions(startView: View?, endView: View?): Array? { if (windowLayoutInfo == null || startView == null || endView == null) { return null } // Calculate the area for view's content with padding. val paddedWidth = width - paddingLeft - paddingRight val paddedHeight = height - paddingTop - paddingBottom windowLayoutInfo?.displayFeatures ?.firstOrNull { feature -> isValidFoldFeature(feature) } ?.let { feature -> getFeaturePositionInViewRect(feature, this)?.let { if (feature.bounds.left == 0) { // Horizontal layout. val topRect = Rect( paddingLeft, paddingTop, paddingLeft + paddedWidth, it.top ) val bottomRect = Rect( paddingLeft, it.bottom, paddingLeft + paddedWidth, paddingTop + paddedHeight ) if (measureAndCheckMinSize(topRect, startView) && measureAndCheckMinSize(bottomRect, endView) ) { return arrayOf(topRect, bottomRect) } } else if (feature.bounds.top == 0) { // Vertical layout. val leftRect = Rect( paddingLeft, paddingTop, it.left, paddingTop + paddedHeight ) val rightRect = Rect( it.right, paddingTop, paddingLeft + paddedWidth, paddingTop + paddedHeight ) if (measureAndCheckMinSize(leftRect, startView) && measureAndCheckMinSize(rightRect, endView) ) { return arrayOf(leftRect, rightRect) } } } } // You previously tried to fit the children and measure them. Since they // don't fit, measure again to update the stored values. measure(lastWidthMeasureSpec, lastHeightMeasureSpec) return null } override fun onMeasure(widthMeasureSpec: Int, heightMeasureSpec: Int) { super.onMeasure(widthMeasureSpec, heightMeasureSpec) lastWidthMeasureSpec = widthMeasureSpec lastHeightMeasureSpec = heightMeasureSpec } /** * Measures a child view and sees if it fits in the provided rect. * This method calls [View.measure] on the child view, which updates its * stored values for measured width and height. If the view ends up with * different values, measure again. */ private fun measureAndCheckMinSize(rect: Rect, childView: View): Boolean { val widthSpec = MeasureSpec.makeMeasureSpec(rect.width(), AT_MOST) val heightSpec = MeasureSpec.makeMeasureSpec(rect.height(), AT_MOST) childView.measure(widthSpec, heightSpec) return childView.measuredWidthAndState and MEASURED_STATE_TOO_SMALL == 0 && childView.measuredHeightAndState and MEASURED_STATE_TOO_SMALL == 0 } private fun isValidFoldFeature(displayFeature: DisplayFeature) = (displayFeature as? FoldingFeature)?.let { feature -> getFeaturePositionInViewRect(feature, this) != null } ?: false }
Java
/** * An example of split-layout for two views, separated by a display feature * that goes across the window. When both start and end views are added, it checks * whether there are display features that separate the area in two—such as * fold or hinge—and places them side-by-side or top-bottom. */ public class SplitLayout extends FrameLayout { @Nullable private WindowLayoutInfo windowLayoutInfo = null; private int startViewId = 0; private int endViewId = 0; private int lastWidthMeasureSpec = 0; private int lastHeightMeasureSpec = 0; ... void updateWindowLayout(WindowLayoutInfo windowLayoutInfo) { this.windowLayoutInfo = windowLayoutInfo; requestLayout(); } @Override protected void onLayout(boolean changed, int left, int top, int right, int bottom) { @Nullable View startView = findStartView(); @Nullable View endView = findEndView(); @Nullable ListsplitPositions = splitViewPositions(startView, endView); if (startView != null && endView != null && splitPositions != null) { Rect startPosition = splitPositions.get(0); int startWidthSpec = MeasureSpec.makeMeasureSpec(startPosition.width(), EXACTLY); int startHeightSpec = MeasureSpec.makeMeasureSpec(startPosition.height(), EXACTLY); startView.measure(startWidthSpec, startHeightSpec); startView.layout( startPosition.left, startPosition.top, startPosition.right, startPosition.bottom ); Rect endPosition = splitPositions.get(1); int endWidthSpec = MeasureSpec.makeMeasureSpec(endPosition.width(), EXACTLY); int endHeightSpec = MeasureSpec.makeMeasureSpec(endPosition.height(), EXACTLY); startView.measure(endWidthSpec, endHeightSpec); startView.layout( endPosition.left, endPosition.top, endPosition.right, endPosition.bottom ); } else { super.onLayout(changed, left, top, right, bottom); } } /** * Gets the position of the split for this view. * @return A rect that defines of split, or {@code null} if there is no split. */ @Nullable private List splitViewPositions(@Nullable View startView, @Nullable View endView) { if (windowLayoutInfo == null || startView == null || endView == null) { return null; } int paddedWidth = getWidth() - getPaddingLeft() - getPaddingRight(); int paddedHeight = getHeight() - getPaddingTop() - getPaddingBottom(); List displayFeatures = windowLayoutInfo.getDisplayFeatures(); @Nullable DisplayFeature feature = displayFeatures .stream() .filter(item -> isValidFoldFeature(item) ) .findFirst() .orElse(null); if (feature != null) { Rect position = SampleToolsKt.getFeaturePositionInViewRect(feature, this, true); Rect featureBounds = feature.getBounds(); if (featureBounds.left == 0) { // Horizontal layout. Rect topRect = new Rect( getPaddingLeft(), getPaddingTop(), getPaddingLeft() + paddedWidth, position.top ); Rect bottomRect = new Rect( getPaddingLeft(), position.bottom, getPaddingLeft() + paddedWidth, getPaddingTop() + paddedHeight ); if (measureAndCheckMinSize(topRect, startView) && measureAndCheckMinSize(bottomRect, endView)) { ArrayList rects = new ArrayList (); rects.add(topRect); rects.add(bottomRect); return rects; } } else if (featureBounds.top == 0) { // Vertical layout. Rect leftRect = new Rect( getPaddingLeft(), getPaddingTop(), position.left, getPaddingTop() + paddedHeight ); Rect rightRect = new Rect( position.right, getPaddingTop(), getPaddingLeft() + paddedWidth, getPaddingTop() + paddedHeight ); if (measureAndCheckMinSize(leftRect, startView) && measureAndCheckMinSize(rightRect, endView)) { ArrayList rects = new ArrayList (); rects.add(leftRect); rects.add(rightRect); return rects; } } } // You previously tried to fit the children and measure them. Since // they don't fit, measure again to update the stored values. measure(lastWidthMeasureSpec, lastHeightMeasureSpec); return null; } @Override protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) { super.onMeasure(widthMeasureSpec, heightMeasureSpec); lastWidthMeasureSpec = widthMeasureSpec; lastHeightMeasureSpec = heightMeasureSpec; } /** * Measures a child view and sees if it fits in the provided rect. * This method calls [View.measure] on the child view, which updates * its stored values for measured width and height. If the view ends up with * different values, measure again. */ private boolean measureAndCheckMinSize(Rect rect, View childView) { int widthSpec = MeasureSpec.makeMeasureSpec(rect.width(), AT_MOST); int heightSpec = MeasureSpec.makeMeasureSpec(rect.height(), AT_MOST); childView.measure(widthSpec, heightSpec); return (childView.getMeasuredWidthAndState() & MEASURED_STATE_TOO_SMALL) == 0 && (childView.getMeasuredHeightAndState() & MEASURED_STATE_TOO_SMALL) == 0; } private boolean isValidFoldFeature(DisplayFeature displayFeature) { if (displayFeature instanceof FoldingFeature) { return SampleToolsKt.getFeaturePositionInViewRect(displayFeature, this, true) != null; } else { return false; } } }