Как Android рисует просмотры

Платформа Android просит Activity нарисовать свой макет, когда Activity получает фокус. Платформа 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 и шириной 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 из примера приложения WindowManager . Если SplitLayout имеет два или более дочерних представления, а отображение имеет складку, то два дочерних представления располагаются по обе стороны от складки. В следующем примере показан вариант использования переопределения размеров и макета, но для рабочей среды используйте SlidingPaneLayout , если вам нужно такое поведение.

Котлин

/**
 * 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
}

Джава

/**
* 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;
      }
   }
}