Jak Android generuje widoki

Platforma Androida prosi Activity o rysowanie układu, gdy element Activity zostanie zaznaczony. Platforma Androida obsługuje procedurę rysowania, ale Activity musi wskazywać węzeł główny swojej hierarchii układu.

Platforma Android rysuje węzeł główny układu oraz mierzy i rysuje drzewo układu. Rysuje się, przechodząc po drzewie i renderując każdy element View, który przecina nieprawidłowy region. Każdy obiekt ViewGroup odpowiada za żądanie narysowania każdego z jego elementów podrzędnych przy użyciu metody draw(), a każdy element View odpowiada za rysowanie. Ponieważ drzewo jest przecinane w przedsprzedaży, platforma przyciąga rodziców wcześniej – czyli za ich dziećmi, oraz rysuje rodzeństwo w kolejności, w jakiej znajdują się na drzewie.

Struktura Androida jest tworzona w ramach procesu dwuetapowego: przekazywania wskaźnika i układu. Platforma przekazuje pomiar w elemencie measure(int, int) i przemierza drzewo View z góry. Podczas rekurencji każdy element View przesuwa specyfikacje wymiarów w dół drzewa. Po zakończeniu przebiegu pomiaru każdy View zapisuje pomiary. Platforma wykonuje drugie przejście w obrębie layout(int, int, int, int) i działa od góry. Podczas tego karnetu każdy element nadrzędny odpowiada za pozycjonowanie wszystkich swoich elementów podrzędnych z użyciem rozmiarów obliczonych w przekazywanym pomiarze.

Dwa etapy procesu tworzenia szablonu opisano bardziej szczegółowo w kolejnych sekcjach.

Rozpocznij pomiar pomiaru

Po zwróceniu metody measure() obiektu View ustaw wartości jego getMeasuredWidth() i getMeasuredHeight(), a także wartości wszystkich elementów podrzędnych obiektu View. Zmierzone wartości szerokości i zmierzonej wysokości obiektu View muszą przestrzegać ograniczeń nałożonych przez obiekty nadrzędne obiektu View. Dzięki temu na koniec pomiaru wszyscy rodzice będą akceptować wszystkie pomiary dziecka.

Element nadrzędny View może wywołać metodę measure() więcej niż raz w swoich organizacjach podrzędnych. Na przykład element nadrzędny może zmierzyć elementy podrzędne raz za pomocą nieokreślonych wymiarów, aby określić ich preferowane rozmiary. Jeśli suma nieograniczonych rozmiarów elementów podrzędnych jest za duża lub za mała, element nadrzędny może ponownie wywołać measure() z wartościami, które ograniczają rozmiary elementów podrzędnych.

Wymiary przekazywane w ramach pomiaru wykorzystują 2 klasy. Klasa ViewGroup.LayoutParams określa, jak obiekty View przekazują swoje preferowane rozmiary i pozycje. Klasa podstawowa ViewGroup.LayoutParams opisuje preferowaną szerokość i wysokość elementu View. Dla każdego wymiaru możesz określić jedną z tych wartości:

  • Dokładny wymiar.
  • MATCH_PARENT, co oznacza, że preferowany rozmiar elementu View to rozmiar elementu nadrzędnego pomniejszony o dopełnienie.
  • WRAP_CONTENT, co oznacza, że preferowany rozmiar elementu View jest na tyle duży, aby zmieścić jego zawartość wraz z dopełnieniem.

Istnieją podklasy ViewGroup.LayoutParams dla różnych podklasy: ViewGroup. Na przykład RelativeLayout ma własną podklasę klasy ViewGroup.LayoutParams, która obejmuje możliwość wyśrodkowania obiektów podrzędnych View w poziomie i w pionie.

Obiekty MeasureSpec są używane do przenoszenia wymagań z elementu nadrzędnego do drzewa podrzędnego. MeasureSpec może działać w jednym z 3 trybów:

  • UNSPECIFIED: element nadrzędny na podstawie tej wartości określa wymiar docelowy elementu podrzędnego View. Na przykład obiekt LinearLayout może wywołać w swoim elemencie podrzędnym measure() o wysokości UNSPECIFIED i szerokości EXACTLY 240, aby dowiedzieć się, jaką wysokość chce mieć element podrzędny View przy szerokości 240 pikseli.
  • EXACTLY: obiekt nadrzędny na podstawie tego elementu narzuca dokładny rozmiar dziecku. Musi użyć tego rozmiaru i zagwarantować, że wszystkie jego elementy podrzędne mieszczą się w tym rozmiarze.
  • AT MOST: element nadrzędny używa tego elementu, aby nałożyć maksymalny rozmiar na element podrzędny. Dziecko musi zagwarantować, że ten rozmiar oraz wszystkie jego elementy podrzędne mieszczą się w tym rozmiarze.

Rozpocznij korzystanie z układu

Aby zainicjować układ, wywołaj metodę requestLayout(). Ta metoda jest zwykle wywoływana przez element View, gdy uzna, że nie mieści się już w wyznaczonych granicach.

Wdrażanie niestandardowych pomiarów i logiki układu

Jeśli chcesz wdrożyć niestandardowe pomiary lub logikę układu, zastąp metody, w których jest zaimplementowana: onMeasure(int, int) i onLayout(boolean, int, int, int, int). Metody te są wywoływane odpowiednio przez metody measure(int, int) i layout(int, int, int, int). Nie próbuj zastępować metod measure(int, int) ani layout(int, int) – obie te metody to final, więc nie można ich zastąpić.

Poniższy przykład pokazuje, jak to zrobić w klasie `SplitLayout` w przykładowej aplikacji WindowManager. Jeśli SplitLayout ma co najmniej 2 widoki podrzędne, a wyświetlacz zawiera część strony widoczną po przewinięciu, umieszcza 2 widoki podrzędne po obu stronach części strony widocznej po przewinięciu. Przykład poniżej pokazuje przypadek użycia zastąpienia pomiaru i układu, ale w środowisku produkcyjnym użyj parametru SlidingPaneLayout, jeśli chcesz, aby tak było.

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