Jak Android generuje wyświetlenia

Wypróbuj Compose
Jetpack Compose to zalecany zestaw narzędzi UI dla Androida. Dowiedz się więcej o fazach Compose.

Gdy Activity uzyska fokus, framework Androida poprosi an Activity o narysowanie układu. Framework Androida obsługuje procedurę rysowania, ale Activity musi udostępnić węzeł główny swojej hierarchii układu.

Framework Androida rysuje węzeł główny układu oraz mierzy i rysuje drzewo układu. Rysuje, przechodząc przez drzewo i renderując każdy element View, który przecina nieprawidłowy region. Każdy ViewGroup jest odpowiedzialny za żądanie narysowania każdego z jej elementów podrzędnych za pomocą draw() metody, a każdy View jest odpowiedzialny za narysowanie siebie. Ponieważ drzewo jest przechodzone w kolejności pre-order, framework rysuje elementy nadrzędne przed ich elementami podrzędnymi, czyli za nimi, a elementy równorzędne rysuje w kolejności, w jakiej występują w drzewie.

Framework Androida rysuje układ w 2 etapach: pomiaru i układu. Framework wykonuje etap pomiaru w measure(int, int) i przechodzi przez drzewo View od góry do dołu. Podczas rekurencji każdy element View przekazuje specyfikacje wymiarów w dół drzewa. Na końcu etapu pomiaru każdy element View zapisuje swoje pomiary. Framework wykonuje drugi etap w layout(int, int, int, int) i również przechodzi przez drzewo od góry do dołu. Podczas tego etapu każdy element nadrzędny jest odpowiedzialny za umieszczenie wszystkich swoich elementów podrzędnych za pomocą rozmiarów obliczonych w etapie pomiaru.

Więcej informacji o 2 etapach procesu układu znajdziesz w kolejnych sekcjach.

Rozpoczynanie etapu pomiaru

Gdy metoda measure() obiektu View zwróci wartość, ustaw wartości getMeasuredWidth() i getMeasuredHeight() oraz wartości wszystkich elementów potomnych obiektu View. Wartości zmierzonej szerokości i zmierzonej wysokości obiektu View muszą być zgodne z ograniczeniami nałożonymi przez elementy nadrzędne obiektu View. Dzięki temu na końcu etapu pomiaru wszystkie elementy nadrzędne akceptują pomiary wszystkich swoich elementów podrzędnych.

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

Etap pomiaru używa 2 klas do przekazywania wymiarów. Klasa ViewGroup.LayoutParams służy do przekazywania preferowanych rozmiarów i pozycji przez View obiekty. Podstawowa ViewGroup.LayoutParams klasa opisuje preferowaną szerokość i wysokość View. W przypadku każdego wymiaru można określić jedną z tych wartości:

  • Dokładny wymiar.
  • MATCH_PARENT, co oznacza, że preferowany rozmiar View to rozmiar jego elementu nadrzędnego pomniejszony o dopełnienie.
  • WRAP_CONTENT, co oznacza, że preferowany rozmiar View jest wystarczająco duży, aby objąć jego zawartość, plus dopełnienie.

Istnieją podklasy ViewGroup.LayoutParams dla różnych podklas ViewGroup. Na przykład RelativeLayout ma własną podklasę ViewGroup.LayoutParams która umożliwia wyśrodkowanie elementów podrzędnych View w poziomie i w pionie.

Obiekty MeasureSpec służą do przekazywania wymagań w dół drzewa od elementu nadrzędnego do elementu podrzędnego. MeasureSpec może być w jednym z 3 trybów:

  • UNSPECIFIED: element nadrzędny używa tego trybu do określania docelowego wymiaru elementu podrzędnego View. Na przykład, element LinearLayout może wywołać measure() w przypadku swojego elementu podrzędnego z wysokością ustawioną na UNSPECIFIED i szerokością EXACTLY 240, aby dowiedzieć się, jaką wysokość chce mieć element podrzędny View przy szerokości 240 pikseli.
  • EXACTLY: element nadrzędny używa tego trybu do narzucania dokładnego rozmiaru elementu podrzędnego. Element podrzędny musi używać tego rozmiaru i gwarantować, że wszystkie jego elementy potomne mieszczą się w tym rozmiarze.
  • AT MOST: element nadrzędny używa tego trybu do narzucania maksymalnego rozmiaru elementu podrzędnego. Element podrzędny musi gwarantować, że on i wszystkie jego elementy potomne mieszczą się w tym rozmiarze.

Rozpoczynanie etapu układu

Aby rozpocząć układ, wywołaj requestLayout(). Ta metoda jest zwykle wywoływana przez View w przypadku samego siebie, gdy uważa, że nie mieści się już w swoich granicach.

Implementowanie niestandardowej logiki pomiaru i układu

Jeśli chcesz zaimplementować niestandardową logikę pomiaru lub układu, zastąp metody, w których jest ona zaimplementowana: onMeasure(int, int) i onLayout(boolean, int, int, int, int). Te metody są wywoływane odpowiednio przez 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 są final, więc nie można ich zastąpić.

Poniższy przykład pokazuje, jak to zrobić w klasie `SplitLayout` z przykładowej aplikacji WindowManager. Jeśli SplitLayout ma co najmniej 2 elementy podrzędne i wyświetlacz ma zagięcie, umieszcza 2 elementy podrzędne po obu stronach zagięcia. Poniższy przykład pokazuje przypadek użycia zastępowania pomiaru i układu, ale w przypadku środowiska produkcyjnego, jeśli chcesz uzyskać takie zachowanie, użyj 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;
      }
   }
}