איך Android מושך צפיות

מערכת Android מבקשת Activity כדי לשרטט את הפריסה שלו כאשר המכשיר Activity מקבל מיקוד. ה-framework של Android מטפל בתהליך השרטוט, אבל Activity חייב לספק את הצומת הבסיסי (root) של היררכיית הפריסה שלו.

ה-framework של Android מושך את הצומת הבסיסי (root) של הפריסה, מודד ומשרטט את עץ הפריסה. הוא צייר על ידי הליכה על העץ ורינדור View שחוצה את האזור הלא חוקי. כל ViewGroup אחראי ולבקש שכל אחד מהצאצאים שלה יילקח באמצעות draw() וכל View אחראי לשרטוט עצמו. כי חצו את העץ בהזמנה מראש, המסגרת הרעיונית מושכת הורים לפני כן – ובמילים אחרות, מאחורי ילדים, וציור אחים ואחיות לפי הסדר שבו הם מופיעים בעץ.

במסגרת Android, הפריסה מיושמת בתהליך של שני מעבר: כרטיס מדידה וכרטיס פריסה. מבצע את פעולת ההמרה measure(int, int) והקבוצה מבצע מעבר מלמעלה למטה של העץ View. כל View דוחף מאפיין מפרט במורד העץ במהלך החזרות. בסוף מעבר המדידה, אפליקציית View שומרת את המדידות שלה. ה-framework מבצע את המעבר השני 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.LayoutParams למחלקות משנה שונות של ViewGroup. לדוגמה, ל-RelativeLayout יש דף משלו המחלקה המשנית של ViewGroup.LayoutParams שכוללת את היכולת למרכז צאצא View אובייקטים לרוחב ואנכי.

MeasureSpec אובייקטים שמשמשת לדחיפת דרישות בעץ, מהורה לילד. MeasureSpec יכול להיות ב- אחד משלושה מצבים:

  • UNSPECIFIED: ההורה משתמש במדד הזה כדי לקבוע את מידות היעד של צאצא View. לדוגמה, LinearLayout יכול להתקשר measure() על הצאצא שלו, והגובה שלו מוגדר כ-UNSPECIFIED וברוחב מתוך EXACTLY 240 כדי לגלות מה הגובה של הילד או הילדה View, בהינתן רוחב של 240 פיקסלים.
  • 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) – שתי השיטות האלה הם final, כך שלא ניתן לשנות אותם.

הדוגמה הבאה מראה איך לעשות זאת `SplitLayout` מ- מנהל החלונות אפליקציה לדוגמה. אם ב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
      List splitPositions = 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;
      }
   }
}