In che modo Android traccia le visualizzazioni

Il framework Android chiede a un Activity di tracciare il suo layout quando Activity viene impostato come attivo. Il framework Android gestisce la procedura per il disegno, ma Activity deve fornire il nodo radice della sua gerarchia di layout.

Il framework Android disegna il nodo radice del layout, misura e traccia l'albero del layout. Disegna camminando sull'albero e visualizzando ogni View che incrocia la regione non valida. Ogni ViewGroup deve richiedere che ciascuno dei suoi figli venga disegnato utilizzando il metodo draw() e ogni View è responsabile del disegno stesso. Poiché l'albero viene attraversato in fase di prenotazione, la struttura attira i genitori prima, in altre parole, dietro i figli e i fratelli e le sorelle nell'ordine in cui appaiono nell'albero.

Il framework Android traccia il layout in un processo in due passaggi: una valutazione della misura e una convalida del layout. Il framework esegue il trasferimento della misura in measure(int, int) ed esegue un attraversamento dall'alto verso il basso della struttura ad albero View. Ogni View sposta le specifiche delle dimensioni verso il basso nell'albero durante la ricorsione. Al termine del pass di misura, ogni View memorizza le proprie misurazioni. Il framework esegue la seconda passaggio in layout(int, int, int, int) ed è anche dall'alto verso il basso. Durante questo passaggio, ogni padre è responsabile del posizionamento di tutti i suoi figli utilizzando le dimensioni calcolate nella trasmissione delle misure.

Le due fasi del processo di layout sono descritte in maggiore dettaglio nelle sezioni seguenti.

Avvia una tessera per misurare

Quando viene restituito il metodo measure() di un oggetto View, imposta i relativi valori getMeasuredWidth() e getMeasuredHeight(), insieme a quelli per tutti i discendenti dell'oggetto View. I valori di larghezza e altezza misurati di un oggetto View devono rispettare i vincoli imposti dagli elementi padre dell'oggetto View. Ciò aiuta a garantire che, al termine della misurazione, tutti i genitori accettino tutte le misurazioni dei figli.

Un elemento principale View potrebbe chiamare measure() più volte sui relativi figli. Ad esempio, il publisher principale potrebbe misurare gli elementi secondari una volta con dimensioni non specificate per determinare le dimensioni preferite. Se la somma delle dimensioni non vincolate degli elementi secondari è troppo grande o troppo piccola, l'elemento principale potrebbe richiamare measure() di nuovo con valori che limitano le taglie degli elementi secondari.

Il passaggio della misura utilizza due classi per comunicare le dimensioni. La classe ViewGroup.LayoutParams è il modo in cui gli oggetti View comunicano le loro dimensioni e posizioni preferite. La classe di base ViewGroup.LayoutParams descrive la larghezza e l'altezza preferite della classe View. Per ogni dimensione, è possibile specificare una delle seguenti opzioni:

  • Una dimensione esatta.
  • MATCH_PARENT, che indica che la dimensione preferita per View è quella dell'elemento padre, meno la spaziatura interna.
  • WRAP_CONTENT, il che significa che la dimensione preferita per View è sufficiente per racchiudere i contenuti, più la spaziatura interna.

Esistono sottoclassi di ViewGroup.LayoutParams per diverse sottoclassi di ViewGroup. Ad esempio, RelativeLayout ha la propria sottoclasse ViewGroup.LayoutParams che include la possibilità di centrare gli oggetti View figlio orizzontalmente e verticalmente.

Vengono utilizzati MeasureSpec oggetti per eseguire il push dei requisiti nella struttura ad albero principale. Un MeasureSpec può avere una delle tre modalità seguenti:

  • UNSPECIFIED: l'elemento principale lo utilizza per determinare la dimensione target di un View secondario. Ad esempio, un LinearLayout potrebbe chiamare measure() sul relativo elemento secondario con l'altezza impostata su UNSPECIFIED e una larghezza di EXACTLY 240 per scoprire quanto vuole essere l'unità secondaria View, data una larghezza di 240 pixel.
  • EXACTLY: l'elemento principale lo utilizza per applicare una dimensione esatta all'elemento secondario. L'asset secondario deve utilizzare questa dimensione e garantire che tutti i relativi discendenti rientrino in questa dimensione.
  • AT MOST: l'elemento principale lo utilizza per imporre una dimensione massima all'asset secondario. L'asset secondario deve garantire che questo e tutti i suoi discendenti rientrino in questa dimensione.

Avvia una tessera per il layout

Per avviare un layout, chiama requestLayout(). Questo metodo viene in genere chiamato da un View quando ritiene di non poter rientrare nei suoi limiti.

Implementa una logica di misurazione e layout personalizzata

Se vuoi implementare una logica di layout o di misurazione personalizzata, esegui l'override dei metodi in cui è implementata la logica: onMeasure(int, int) e onLayout(boolean, int, int, int, int). Questi metodi sono richiamati rispettivamente da measure(int, int) e layout(int, int, int, int). Non provare a eseguire l'override dei metodi measure(int, int) o layout(int, int): entrambi sono final, quindi non è possibile eseguirne l'override.

L'esempio seguente mostra come eseguire questa operazione nella classe "SplitLayout" dell'app di esempio WindowManager. Se SplitLayout ha due o più viste secondarie e il display ha un fold, le due visualizzazioni secondarie vengono posizionate su entrambi i lati. L'esempio seguente mostra un caso d'uso per eseguire l'override della misurazione e del layout, ma per la produzione utilizza SlidingPaneLayout se vuoi questo comportamento.

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