מסגרת Android מבקשת מ-Activity לצייר את הפריסה שלו כש-Activity מקבל את המיקוד. ה-framework של Android מטפל בתהליך של ציור, אבל Activity צריך לספק את צומת השורש של היררכיית הפריסה שלו.
מסגרת Android מציירת את צומת הבסיס של הפריסה, ומודדת ומציירת את עץ הפריסה. הוא מצייר על ידי מעבר על העץ ועיבוד כל View שחוצה את האזור הלא תקין.
כל ViewGroup אחראי לבקש מכל אחד מהילדים שלו לצייר את עצמו באמצעות השיטה draw(), וכל View אחראי לצייר את עצמו. מכיוון שהעץ עובר בהזמנה מראש, המסגרת מציירת את ההורים לפני הילדים שלהם, כלומר מאחורי הילדים, ומציירת את האחים לפי הסדר שבו הם מופיעים בעץ.
מסגרת Android מציירת את הפריסה בתהליך של שני שלבים: שלב המדידה ושלב הפריסה. המסגרת מבצעת את שלב המדידה ב-measure(int, int) ומבצעת מעבר מלמעלה למטה בעץ View. כל View מעביר את מפרטי המאפיינים במורד העץ במהלך הרקורסיה. בסוף שלב המדידה, כל View שומר את המדידות שלו. המסגרת מבצעת את המעבר השני ב-layout(int, int, int, int) והיא גם מלמעלה למטה. במהלך המעבר הזה, כל הורה אחראי למיקום כל הילדים שלו באמצעות הגדלים שחושבו במעבר המדידה.
בקטעים הבאים מוסבר בפירוט על שני השלבים בתהליך הפריסה.
התחלת מעבר למדידה
כששיטת measure() של אובייקט View מחזירה ערך, צריך להגדיר את הערכים של getMeasuredWidth() ושל getMeasuredHeight(), וגם את הערכים של כל האובייקטים שצאצאים של אובייקט View. הערכים של הרוחב והגובה הנמדדים של Viewאובייקט צריכים להתאים למגבלות שהוגדרו על ידי אובייקטי האב של Viewהאובייקט. כך אפשר לוודא שבסוף תהליך המדידה, כל ההורים יאשרו את כל המדידות של הילדים שלהם.
הורה View יכול להתקשר measure() לילדים שלו יותר מפעם אחת. לדוגמה, ההורה יכול למדוד את הילדים פעם אחת עם מידות לא מוגדרות כדי לקבוע את המידות המועדפות שלהם. אם סכום הגדלים הלא מוגבלים של רכיבי הצאצא גדול מדי או קטן מדי, יכול להיות שהרכיב האב יקרא שוב לפונקציה measure() עם ערכים שמגבילים את הגדלים של רכיבי הצאצא.
בשלב המדידה נעשה שימוש בשתי מחלקות כדי להעביר מידע על מאפיינים. המחלקות ViewGroup.LayoutParams
משמשות את אובייקטים של View כדי להעביר מידע על הגודל והמיקום המועדפים שלהם. במחלקת הבסיס
ViewGroup.LayoutParams מתואר הרוחב והגובה המועדפים של
View. לכל מאפיין אפשר לציין אחת מהאפשרויות הבאות:
- מאפיין מדויק.
MATCH_PARENT, כלומר הגודל המועדף שלViewהוא הגודל של הרכיב ברמת ההורה, פחות השוליים הפנימיים.WRAP_CONTENT, כלומר הגודל המועדף שלViewהוא בדיוק מספיק גדול כדי להכיל את התוכן שלו, בתוספת מרווח פנימי.
יש מחלקות משנה של ViewGroup.LayoutParams למחלקות משנה שונות של ViewGroup. לדוגמה, ל-RelativeLayout יש מחלקת משנה משלו של ViewGroup.LayoutParams שכוללת את היכולת למרכז אובייקטים של צאצא View אופקית ואנכית.
אובייקטים של MeasureSpec משמשים להעברת דרישות במורד העץ מהורה לצאצא. MeasureSpec יכול להיות באחד משלושת המצבים הבאים:
-
UNSPECIFIED: חשבון ההורה משתמש בזה כדי לקבוע את מימד היעד של חשבון הילדView. לדוגמה, רכיבLinearLayoutעשוי לקרוא לשיטהmeasure()ברכיב הצאצא שלו עם הגובה שמוגדר ל-UNSPECIFIEDורוחב שלEXACTLY240 כדי לגלות מה הגובה שרכיב הצאצאViewרוצה להיות, בהינתן רוחב של 240 פיקסלים. EXACTLY: האלמנט ברמת ההורה משתמש בערך הזה כדי להגדיר גודל מדויק לאלמנט ברמת הצאצא. הילד חייב להשתמש במידה הזו ולהבטיח שכל צאצאיו יתאימו למידה הזו.-
AT MOST: החשבון הראשי משתמש בערך הזה כדי להגביל את הגודל המקסימלי של החשבון המשני. הילד חייב להבטיח שהוא וכל הצאצאים שלו מתאימים לגודל הזה.
הפעלת מעבר פריסה
כדי להפעיל פריסה, מתקשרים אל requestLayout(). בדרך כלל השיטה הזו נקראת על ידי View בעצמה כשהיא חושבת שהיא כבר לא יכולה להתאים לגבולות שלה.
הטמעה של לוגיקה מותאמת אישית של מדידה ופריסה
אם רוצים להטמיע מדידה מותאמת אישית או לוגיקה של פריסה, צריך לבטל את השיטות שבהן הלוגיקה מוטמעת:
onMeasure(int, int)
ו-
onLayout(boolean, int, int, int, int).
ה-methods האלה נקראות measure(int, int) ו-layout(int, int, int, int), בהתאמה. אל תנסו לבטל את השיטות measure(int, int) או layout(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; } } }