Il framework Android chiede a un
Activity di disegnare il suo layout quando
Activity riceve lo stato attivo. Il framework Android gestisce la procedura di disegno, ma il
Activity deve fornire il nodo radice della gerarchia del layout.
Il framework Android disegna il nodo radice del layout e misura e disegna l'albero del layout. Disegna
percorrendo la struttura e visualizzando ogni
View che interseca la regione non valida.
Ogni ViewGroup è responsabile
di richiedere che ciascuno dei suoi figli venga disegnato utilizzando il metodo
draw() e ogni View è responsabile di disegnare se stesso. Poiché l'albero viene attraversato
in pre-ordine, il framework disegna i genitori prima, ovvero dietro, i figli e i fratelli nell'ordine in cui compaiono nell'albero.
Il framework Android disegna il layout in un processo in due passaggi: un passaggio di misurazione e un passaggio di layout. Il
framework esegue il passaggio di misurazione in
measure(int, int) ed
esegue un attraversamento dall'alto verso il basso dell'albero View. Ogni View inserisce le specifiche
della dimensione nell'albero durante la ricorsione. Al termine della misurazione, ogni
View memorizza le proprie misurazioni. Il framework esegue il secondo passaggio in
layout(int, int, int, int)
ed è anche top-down. Durante questa passata, ogni genitore è responsabile del posizionamento di tutti i suoi figli
utilizzando le dimensioni calcolate nella passata di misurazione.
Le due passate della procedura di layout sono descritte in modo più dettagliato nelle sezioni seguenti.
Avviare un passaggio di misura
Quando viene restituito il metodo measure() di un oggetto View, imposta i valori getMeasuredWidth() e getMeasuredHeight(), insieme a quelli di tutti i discendenti dell'oggetto View. I valori di larghezza misurata e altezza misurata di un oggetto View devono rispettare i vincoli imposti dai genitori dell'oggetto View. In questo modo, alla fine del passaggio della misurazione, tutti i genitori
accettano tutte le misurazioni dei figli.
Un genitore View potrebbe chiamare measure() più di una volta per i suoi figli. Ad esempio, il genitore potrebbe misurare i bambini una volta con dimensioni non specificate per determinare le loro taglie preferite. Se la somma delle dimensioni non vincolate degli elementi secondari è troppo grande o troppo piccola, l'elemento principale
potrebbe chiamare di nuovo measure() con valori che vincolano le dimensioni degli elementi secondari.
La tessera di misurazione utilizza due classi per comunicare le dimensioni. La classe
ViewGroup.LayoutParams
è il modo in cui gli oggetti View comunicano le dimensioni e le posizioni preferite. La classe base
ViewGroup.LayoutParams descrive la larghezza e l'altezza preferite di
View. Per ogni dimensione, può specificare una delle seguenti opzioni:
- Una dimensione esatta.
MATCH_PARENT, il che significa che la dimensione preferita perViewè la dimensione del relativo elemento padre, meno il padding.WRAP_CONTENT, ovvero la dimensione preferita perViewè appena sufficiente a contenere i contenuti, più il padding.
Esistono sottoclassi di ViewGroup.LayoutParams per diverse sottoclassi di
ViewGroup. Ad esempio,
RelativeLayout ha una propria
sottoclasse di ViewGroup.LayoutParams che include la possibilità di centrare gli oggetti
View secondari orizzontalmente e verticalmente.
Gli oggetti MeasureSpec vengono utilizzati per trasferire i requisiti verso il basso nella struttura ad albero, dall'elemento principale all'elemento secondario. Un MeasureSpec può essere in
una delle tre modalità:
UNSPECIFIED: il genitore lo utilizza per determinare la dimensione target di unViewfiglio. Ad esempio, unLinearLayoutpotrebbe chiamaremeasure()sul suo elemento figlio con l'altezza impostata suUNSPECIFIEDe una larghezza diEXACTLY240 per scoprire l'altezza che l'elemento figlioViewvuole avere, data una larghezza di 240 pixel.EXACTLY: il genitore lo utilizza per imporre una dimensione esatta al figlio. Il bambino deve utilizzare questa dimensione e garantire che tutti i suoi discendenti rientrino in questa dimensione.AT MOST: il genitore lo utilizza per imporre una dimensione massima al figlio. Il bambino deve garantire che lui e tutti i suoi discendenti rientrino in queste dimensioni.
Avviare un layout pass
Per avviare un layout, chiama
requestLayout(). Questo
metodo viene in genere chiamato da un View su se stesso quando ritiene di non poter più rientrare
nei suoi limiti.
Implementare una logica di misurazione e layout personalizzata
Se vuoi implementare una logica di misurazione o layout personalizzata, esegui l'override dei metodi in cui viene implementata la logica:
onMeasure(int, int)
e
onLayout(boolean, int, int, int, int).
Questi metodi vengono chiamati rispettivamente da measure(int, int) e
layout(int, int, int, int). Non tentare di ignorare i metodi
measure(int, int) o layout(int, int). Entrambi i metodi
sono final, quindi non possono essere ignorati.
L'esempio seguente mostra come eseguire questa operazione nella classe `SplitLayout` dell'app di esempio WindowManager. Se SplitLayout ha due o più visualizzazioni secondarie e il display ha una piega, posiziona le due visualizzazioni secondarie su entrambi i lati della piega. L'esempio seguente mostra un caso d'uso per 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 ListsplitPositions = 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; } } }