كيفية جذب Android للمشاهدات

يسأل إطار عمل Android Activity لرسم تنسيقه عند يتم التركيز على "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.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 تعرض مشاهدتَين ثانويتَين أو أكثر وكانت الشاشة قابلة للطي، ثم يتم وضع العرضَين الثانويَين على أي من جانبَي الجزء المرئي من الصفحة. يوضح المثال التالي إحدى الاستخدامات حالة لإلغاء القياس والتخطيط، ولكن للإنتاج، استخدم 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;
      }
   }
}