FrameLayout源碼淺析

FrameLayout是一個ViewGroup。在ViewGroup最重要的兩步方法是測量和布局:onMeasure()、onLayout()方法。所以這里只分析FrameLayout的onMeasure()、onLayout()方法。

FrameLayout的特征:
FrameLayout的所有子View一般都是在容器的左上方,除非子View有設置layout_gravity這個屬性。

FrameLayout的onMeasure()源碼:
流程:FrameLayout的onMeasure(),會先遍歷所有子View,并為每個子View確定MeasureSpec,計算出子view中最大的寬度和高度,并把寬或高是match_parent的子view放進一個List集合中。把子view的最大寬高度+padding,然后調用setMeasuredDimension()方法,根據frameLayout的MeasureSpec和最大寬高度確認FrameLayout的大小。之后把剛剛match_parent的子view集合遍歷,根據已經確定了FrameLayout的大小再重新計算設置這個子View的MeasureSpec

private final ArrayList<View> mMatchParentChildren = new ArrayList<>(1);
  @Override
  protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
      int count = getChildCount();
      //是否大小已經確定,不需要子view的和大小來確定
      final boolean measureMatchParentChildren =
              MeasureSpec.getMode(widthMeasureSpec) != MeasureSpec.EXACTLY ||
              MeasureSpec.getMode(heightMeasureSpec) != MeasureSpec.EXACTLY;
      //父類可以會多次調用onMeasure,為了避免數據疊加,每次先清空數據
      mMatchParentChildren.clear();

      int maxHeight = 0;
      int maxWidth = 0;
      int childState = 0;

      //測量所有子View,并記錄最大的寬高
      for (int i = 0; i < count; i++) {
          final View child = getChildAt(i);
          if (mMeasureAllChildren || child.getVisibility() != GONE) {
              //這里是設置子view的measureSpec,并調用子view的onmeasure方法,與getChildMeasureSpec()不同的是,這個measureChildMargin()方法把margin也去除了。
              measureChildWithMargins(child, widthMeasureSpec, 0, heightMeasureSpec, 0);
              final LayoutParams lp = (LayoutParams) child.getLayoutParams();
              maxWidth = Math.max(maxWidth,
                      child.getMeasuredWidth() + lp.leftMargin + lp.rightMargin);
              maxHeight = Math.max(maxHeight,
                      child.getMeasuredHeight() + lp.topMargin + lp.bottomMargin);
              childState = combineMeasuredStates(childState, child.getMeasuredState());
              //
              if (measureMatchParentChildren) {
                  if (lp.width == LayoutParams.MATCH_PARENT ||
                          lp.height == LayoutParams.MATCH_PARENT) {
                      mMatchParentChildren.add(child);
                  }
              }
          }
      }

      //最大寬高加上padding
      // Account for padding too
      maxWidth += getPaddingLeftWithForeground() + getPaddingRightWithForeground();
      maxHeight += getPaddingTopWithForeground() + getPaddingBottomWithForeground();

      // Check against our minimum height and width
      maxHeight = Math.max(maxHeight, getSuggestedMinimumHeight());
      maxWidth = Math.max(maxWidth, getSuggestedMinimumWidth());

      // Check against our foreground's minimum height and width
      final Drawable drawable = getForeground();
      if (drawable != null) {
          maxHeight = Math.max(maxHeight, drawable.getMinimumHeight());
          maxWidth = Math.max(maxWidth, drawable.getMinimumWidth());
      }

      //主要處理viewGroup的at_most、unspecified兩種模式的大小,at_most:大小不能超過父viewGroup默認大小,unspecified默認是子view所需的大小
      setMeasuredDimension(resolveSizeAndState(maxWidth, widthMeasureSpec, childState),
              resolveSizeAndState(maxHeight, heightMeasureSpec,
                      childState << MEASURED_HEIGHT_STATE_SHIFT));

      //將所有子view的寬高的是match_parent的記錄下來,然后重新賦值這些子view的寬高
      count = mMatchParentChildren.size();
      if (count > 1) {
          for (int i = 0; i < count; i++) {
              final View child = mMatchParentChildren.get(i);
              final MarginLayoutParams lp = (MarginLayoutParams) child.getLayoutParams();

              //寬度
              final int childWidthMeasureSpec;
              if (lp.width == LayoutParams.MATCH_PARENT) {
                  final int width = Math.max(0, getMeasuredWidth()
                          - getPaddingLeftWithForeground() - getPaddingRightWithForeground()
                          - lp.leftMargin - lp.rightMargin);
                  childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
                          width, MeasureSpec.EXACTLY);
              } else {
                  childWidthMeasureSpec = getChildMeasureSpec(widthMeasureSpec,
                          getPaddingLeftWithForeground() + getPaddingRightWithForeground() +
                          lp.leftMargin + lp.rightMargin,
                          lp.width);
              }

              final int childHeightMeasureSpec;
              if (lp.height == LayoutParams.MATCH_PARENT) {
                  final int height = Math.max(0, getMeasuredHeight()
                          - getPaddingTopWithForeground() - getPaddingBottomWithForeground()
                          - lp.topMargin - lp.bottomMargin);
                  childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
                          height, MeasureSpec.EXACTLY);
              } else {
                  childHeightMeasureSpec = getChildMeasureSpec(heightMeasureSpec,
                          getPaddingTopWithForeground() + getPaddingBottomWithForeground() +
                          lp.topMargin + lp.bottomMargin,
                          lp.height);
              }

              //給match_parent的子view重新設置大小
              //這里又調用了子View的measure()方法,在上面的確定子view的measureSpec已經調用了一次,所以子view可能會被父view調用多次onMeasure(),要記得數據清楚。
              child.measure(childWidthMeasureSpec, childHeightMeasureSpec);
          }
      }
  }

FrameLayout的match_parent的子view會被調用兩次onMeasure,所以再onMeasure()要注意數據的清楚,FrameLayout這里onMeasure也是每調用一次就會清除List的集合。大概實現思路是:先記錄子View的最大寬高->確定FrameLayout自己的大小->重新設置width、height是match_parent的大小。

FrameLayout的onLayout()源碼:
onLayout布局再FrameLayout的大小確定之后,因為其子View不用涉及到換行等問題,一般子view如果不設置gravity的屬性,默認是在FrameLayout左上顯示。所以這里的布局,只需要判斷gravity的屬性,然后根據屬性值來動態確認left和top的位置

//frameLayout所有的子View都是從容器左上方開始,除了一個gravity
  @Override
  protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
      layoutChildren(left, top, right, bottom, false /* no force left gravity */);
  }

  void layoutChildren(int left, int top, int right, int bottom, boolean forceLeftGravity) {
      final int count = getChildCount();

      final int parentLeft = getPaddingLeftWithForeground();
      final int parentRight = right - left - getPaddingRightWithForeground();

      final int parentTop = getPaddingTopWithForeground();
      final int parentBottom = bottom - top - getPaddingBottomWithForeground();

      for (int i = 0; i < count; i++) {
          final View child = getChildAt(i);
          if (child.getVisibility() != GONE) {
              final LayoutParams lp = (LayoutParams) child.getLayoutParams();

              final int width = child.getMeasuredWidth();
              final int height = child.getMeasuredHeight();

              int childLeft;
              int childTop;

              int gravity = lp.gravity;
              if (gravity == -1) {
                  gravity = DEFAULT_CHILD_GRAVITY;
              }

              final int layoutDirection = getLayoutDirection();
              final int absoluteGravity = Gravity.getAbsoluteGravity(gravity, layoutDirection);
              final int verticalGravity = gravity & Gravity.VERTICAL_GRAVITY_MASK;

              switch (absoluteGravity & Gravity.HORIZONTAL_GRAVITY_MASK) {
                  case Gravity.CENTER_HORIZONTAL:
                      childLeft = parentLeft + (parentRight - parentLeft - width) / 2 +
                      lp.leftMargin - lp.rightMargin;
                      break;
                  case Gravity.RIGHT:
                      if (!forceLeftGravity) {
                          childLeft = parentRight - width - lp.rightMargin;
                          break;
                      }
                  case Gravity.LEFT:
                  default:
                      childLeft = parentLeft + lp.leftMargin;
              }

              switch (verticalGravity) {
                  case Gravity.TOP:
                      childTop = parentTop + lp.topMargin;
                      break;
                  case Gravity.CENTER_VERTICAL:
                      childTop = parentTop + (parentBottom - parentTop - height) / 2 +
                      lp.topMargin - lp.bottomMargin;
                      break;
                  case Gravity.BOTTOM:
                      childTop = parentBottom - height - lp.bottomMargin;
                      break;
                  default:
                      childTop = parentTop + lp.topMargin;
              }

              child.layout(childLeft, childTop, childLeft + width, childTop + height);
          }
      }
  }
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,345評論 6 531
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,494評論 3 416
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,283評論 0 374
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 62,953評論 1 309
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,714評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,186評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,255評論 3 441
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,410評論 0 288
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,940評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,776評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,976評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,518評論 5 359
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,210評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,642評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,878評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,654評論 3 391
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,958評論 2 373

推薦閱讀更多精彩內容