Android nasıl görüntüleme çeker?

Android çerçevesi, kullanıcılara öğesini seçtiğinizde düzeni çizmek için Activity Activity odağı alır. Android çerçevesi çizim işlemini gerçekleştirir 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ü alır ve düzen ağacını ölçüp çizer. Google tek bir resimle birlikte çalışarak View geçersiz bölgeyle kesişiyor. Her ViewGroup şunlardan sorumludur: kullanılarak, tablodaki alt öğelerin her birinin draw() yöntemini kullanır ve her View kendisinin çiziminden sorumludur. Ağaç boyunca geçildiği için bu çerçeve, ebeveynleri kendilerinden önce, diğer bir deyişle arkasında çeker. kardeşleri ağaçta göründükleri sırayla çeker.

Android çerçevesi, düzeni iki geçişli bir süreçle çizer: ölçüm aktarımı ve düzen geçişi. İlgili içeriği oluşturmak için kullanılan çerçeve, paydaşlara iletmek için measure(int, int) ve View ağacında yukarıdan aşağıya geçiş yapar. Her View, boyut aktarır yineleme sırasında ağacın alt kısmındaki teknik özellikleri devreye sokmaktır. Ölçme geçişinin sonunda, View, ölçümlerini depolar. Çerçeve, ikinci geçişi layout(int, int, int, int). yukarıdan aşağıya bakar. Bu kartta her çocuk kendi çocuklarının konumunu belirlemekten sorumludur. hesaplanan boyutları kullanabilirsiniz.

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

Ölçüm kartı başlatın

View nesnesi measure() yöntem döner, getMeasuredWidth() ve getMeasuredHeight() değerleriyle birlikte View nesnesinin alt öğelerinin tümüne ilişkin değerler içerir. View nesnenin ölçülen genişliği ve ölçülen yükseklik değerleri, View nesnesinin üst öğeleri. Bu sayede, ölçüm geçişi sonunda tüm ebeveynler, kabul etmesi gerekir.

View adlı ebeveyn, alt kuruluşlarında measure() adlı kişiyi birden fazla kez arayabilir. Örneğin, Örneğin üst, alt öğeleri belirlemek için boyutları belirtilmemiş tercih edilen boyutlar. Alt öğelerin kısıtlanmamış boyutlarının toplamı çok büyük veya çok küçükse , alt öğelerin boyutlarını sınırlayan değerlerle measure() öğesini tekrar çağırabilir.

Ölçüm aktarımı, boyutları iletmek için iki sınıf kullanır. İlgili içeriği oluşturmak için kullanılan ViewGroup.LayoutParams. sınıfı, View nesnelerin tercih ettikleri boyut ve konumları ilettiğini belirtir. Temel ViewGroup.LayoutParams sınıfı, View. Her boyut için aşağıdakilerden birini belirtebilir:

  • Tam boyut.
  • MATCH_PARENT Diğer bir deyişle, View için tercih edilen boyut, üst öğenin boyutudur. dolgu.
  • WRAP_CONTENT Yani View için tercih edilen boyut, içeriğini kapsayacak kadar büyüktür. artı dolgusu vardır.

Şu sınıfın farklı alt sınıfları için ViewGroup.LayoutParams alt sınıfları vardır: ViewGroup. Örneğin, RelativeLayout kendine ait çocuğu ortalama yeteneğini içeren ViewGroup.LayoutParams alt sınıfı Yatay ve dikey View nesne.

MeasureSpec nesne bu gereklilikleri üst ağdan alt öğeye taşımak için kullanılır. MeasureSpec olabilir üç moddan biri:

  • UNSPECIFIED: üst öğe, bunu bir alt View öğesinin hedef boyutunu belirlemek için kullanır. Örneğin, LinearLayout telefon edebilir Yüksekliği UNSPECIFIED ve genişliği UNSPECIFIED olarak ayarlanmış alt öğesi üzerinde measure() / EXACTLY 240 (240 piksel genişliğinde, View adlı alt çocuğun ne kadar uzun olmasını istediğini) öğrenmek için kullanılır.
  • EXACTLY: ebeveyn, çocuğa tam bir beden ölçüsü uygulamak için bunu kullanır. Çocuk, bu boyutu ve tüm alt öğelerinin bu boyuta uyacağını garanti edebilir.
  • AT MOST: üst öğe, çocuğa maksimum bir boyut uygulamak için bunu kullanır. Çocuk, kendisinin ve tüm alt öğeleri bu boyuta sığar.

Düzen pasosu başlatın

Bir düzeni başlatmak için requestLayout() Bu yöntem, artık sığmadığına inandığında genellikle kendi üzerinde View tarafından çağrılır kabul etmesi gerekir.

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

Özel bir ölçüm veya düzen mantığı uygulamak istiyorsanız mantığın etkinleştirildiği yöntemleri geçersiz kılın. uygulandığında: onMeasure(int, int). ve onLayout(boolean, int, int, int, int). Bu yöntemler measure(int, int) ve Sırasıyla layout(int, int, int, int). Lütfen measure(int, int) veya layout(int, int) yöntemleri (bu yöntemlerin her ikisi de) final olduğu için geçersiz kılınamazlar.

Aşağıdaki örnekte, "SplitLayout" şuradan sınıfa: Pencere Yöneticisi örnek uygulama. SplitLayout için iki veya daha fazla çocuk görüntülemesi varsa ve ekranda ekran sınırı varsa Ardından, ekranın her iki tarafına da çocukların bakmasını sağlayacak konuma getirir. Aşağıdaki örnekte, ölçüm ve düzeni geçersiz kılmak için kullanılabilir ancak üretim için SlidingPaneLayout. bunu yapabilirsiniz.

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