Android nasıl Görünüm çeker?

Android çerçevesi, Activity odak aldığında bir Activity öğesinden düzenini çizmesini ister. Android çerçevesi, çizim prosedürünü yürütür ancak Activity, düzen hiyerarşisinin kök düğümünü sağlamalıdır.

Android çerçevesi, düzenin kök düğümünü çizer ve düzen ağacını ölçer ve çizer. Ağacı yürütürken ve geçersiz bölgeyle kesişen her View oluşturarak çizim yapar. Her ViewGroup, draw() yöntemini kullanarak alt öğelerinin çizilmesini talep etmekten ve her View kendi çiziminden sorumludur. Ağaçta ön sıralamadan geçildiği için çerçeve, ebeveynleri çocuklarının arkasına, kardeşleri ise ağaçta göründükleri sırayla çizer.

Android çerçevesi, düzeni iki geçişli bir süreçte çizer: ölçüm geçişi ve düzen geçişi. Çerçeve, measure(int, int) içinde ölçüm geçişi yapar ve View ağacında yukarıdan aşağıya geçiş gerçekleştirir. Her View, yineleme sırasında boyut özelliklerini ağacın aşağısına aktarır. Ölçüm geçişinin sonunda her View kendi ölçümlerini depolar. Çerçeve, ikinci geçişi layout(int, int, int, int) içinde gerçekleştirir ve aynı zamanda yukarıdan aşağıya doğrudur. Bu geçiş sırasında her üst, ölçüm geçişinde hesaplanan boyutları kullanarak tüm alt öğelerini konumlandırmaktan sorumludur.

Düzen işleminin iki geçişi, sonraki bölümlerde daha ayrıntılı olarak açıklanmaktadır.

Ölçüm pasosu başlatın

Bir View nesnesinin measure() yöntemi döndürüldüğünde, getMeasuredWidth() ve getMeasuredHeight() değerlerini, View nesnesinin tüm alt öğeleri için değerlerle birlikte ayarlayın. Bir View nesnesinin ölçülen genişliği ve ölçülen yükseklik değerleri, View nesnesinin üst öğeleri tarafından uygulanan kısıtlamalara uymalıdır. Bu, tüm ebeveynlerin, önlem geçiminden sonra çocuklarının tüm ölçümlerini kabul etmesini sağlar.

Bir üst View, alt öğelerinde measure() öğesini birden çok kez çağırabilir. Örneğin, üst öğe, tercih edilen boyutları belirlemek için alt öğeleri belirtilmemiş boyutlarla bir kez ölçebilir. Alt öğelerin kısıtlanmamış boyutlarının toplamı çok büyük veya çok küçükse üst öğe, alt öğelerin boyutlarını kısıtlayan değerlerle measure() öğesini tekrar çağırabilir.

Ölçüm geçişi, boyutları iletmek için iki sınıf kullanır. ViewGroup.LayoutParams sınıfı, View nesnelerinin tercih ettikleri boyutları ve konumları nasıl ilettiğini belirler. Temel ViewGroup.LayoutParams sınıfı, View öğesinin tercih edilen genişliğini ve yüksekliğini tanımlar. Her boyut için aşağıdakilerden birini belirtebilir:

  • Tam boyuttur.
  • MATCH_PARENT; diğer bir deyişle, View için tercih edilen boyut, dolgunun çıkarıldığı üst öğe boyutudur.
  • WRAP_CONTENT; yani View için tercih edilen boyut, içeriği ve dolguyu kapsayacak kadar büyüktür.

Farklı ViewGroup alt sınıfları için ViewGroup.LayoutParams alt sınıfları vardır. Örneğin, RelativeLayout, alt View nesnelerini yatay ve dikey olarak ortalayabilme özelliğini içeren kendi ViewGroup.LayoutParams alt sınıfına sahiptir.

Gereksinimleri ağacın üst kısmından alt öğeye aktarmak için MeasureSpec nesneleri kullanılır. MeasureSpec, üç moddan birinde olabilir:

  • UNSPECIFIED: Üst öğe, View alt öğesinin hedef boyutunu belirlemek için bunu kullanır. Örneğin, bir LinearLayout, 240 piksellik bir genişlik verildiğinde, View alt öğesinin ne kadar uzun olmak istediğini öğrenmek için yüksekliği UNSPECIFIED ve genişliği EXACTLY 240 olacak şekilde alt öğesinde measure() çağırabilir.
  • EXACTLY: Ebeveyn, çocuğa tam bir beden uygulamak için bunu kullanır. Çocuk bu boyutu kullanmalı ve tüm alt öğelerinin bu boyuta sığmasını garanti etmelidir.
  • AT MOST: Ebeveyn, çocuğa maksimum boyut uygulamak için bunu kullanır. Çocuk, kendinin ve tüm alt öğelerinin bu boyuta sığmasını garanti etmelidir.

Düzen geçişini başlatın

Bir düzen başlatmak için requestLayout() çağrısı yapın. Bu yöntem, artık sınırlarına uymayacağını düşündüğünde genellikle tek başına bir View tarafından çağrılır.

Özel bir ölçüm ve düzen mantığı uygulama

Özel bir ölçüm veya düzen mantığı uygulamak istiyorsanız mantığın uygulandığı yöntemleri geçersiz kılın: onMeasure(int, int) ve onLayout(boolean, int, int, int, int). Bu yöntemler sırasıyla measure(int, int) ve layout(int, int, int, int) tarafından adlandırılır. measure(int, int) veya layout(int, int) yöntemlerini geçersiz kılmaya çalışmayın. Bu yöntemlerin ikisi de final olduğundan geçersiz kılınamaz.

Aşağıdaki örnekte, WindowManager örnek uygulamasındaki "SplitLayout" sınıfında nasıl yapılacağı gösterilmektedir. SplitLayout iki veya daha fazla alt görünüm içeriyorsa ve ekranda bir katlı ekran varsa iki alt görünüm, ekranın her iki tarafına da yerleştirilecektir. Aşağıdaki örnekte, ölçümü ve düzeni geçersiz kılmaya ilişkin bir kullanım alanı gösterilmektedir ancak üretim söz konusu olduğunda bu davranışı istiyorsanız SlidingPaneLayout özelliğini kullanın.

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