【view】- setContentView方法和UI绘制流程(源码分析)

目录

【view】- 测量流程
【view】- 布局流程
【view】- 绘制流程

简介

setContentView大家都不陌生,在Activity中,通过setContentView方法传入布局文件id来加载我们的布局。那加载过程到达做了那些操作,展现在手机屏幕前的UI又是怎么组成的呢?下面将一一揭晓。

SDK版本

Android API 26(代码分析使用)。
Android 8.0系统源码(部分系统布局文件,类如果在sdk找不到)。

视图结构

这张图是从网上找的,下面讲的可以能有一点不同,但是结构是一样的。


视图结构.jpeg

setContentView

如果使用的是AppCompatActivity,那么会执行AppCompatDelegateImpl中对应的setContentView方法。

@Override
public void setContentView(int resId) {
    ensureSubDecor();
    ViewGroup contentParent = (ViewGroup) mSubDecor.findViewById(android.R.id.content);
    contentParent.removeAllViews();
    LayoutInflater.from(mContext).inflate(resId, contentParent);
    mOriginalWindowCallback.onContentChanged();
}
ensureSubDecor
  • 初始化mSubDecor实例
    首先获取Activity主题,然后根据不同的主题设置窗口特征属性。

    根据不同的Activity窗口类型,通过LayoutInflater加载不同的布局文件,然后赋值给subDecor变量,如果subDecor等于null,者直接抛出异常。

    我们以加载这个布局为例,一起看看结构组成。

    subDecor = (ViewGroup) LayoutInflater.from(themedContext)
                          .inflate(R.layout.abc_screen_toolbar, null);
    

    layout.abc_screen_toolbar.xml文件内容

    <android.support.v7.widget.ActionBarOverlayLayout
          ...
          android:id="@+id/decor_content_parent"
          ...
          android:fitsSystemWindows="true">
      <include layout="@layout/abc_screen_content_include"/>
      <android.support.v7.widget.ActionBarContainer
              android:id="@+id/action_bar_container"
              android:layout_width="match_parent"
              android:layout_height="wrap_content"
              android:layout_alignParentTop="true"
              style="?attr/actionBarStyle"
              android:touchscreenBlocksFocus="true"
              android:gravity="top">
          <android.support.v7.widget.Toolbar
                  android:id="@+id/action_bar"
                  android:layout_width="match_parent"
                  android:layout_height="wrap_content"  
                  ...              
                  style="?attr/toolbarStyle"/>
          <android.support.v7.widget.ActionBarContextView
                  android:id="@+id/action_context_bar"
                  android:layout_width="match_parent"
                  android:layout_height="wrap_content"
                  android:visibility="gone"
                  android:theme="?attr/actionBarTheme"
                  style="?attr/actionModeStyle"/>
      </android.support.v7.widget.ActionBarContainer>
    </android.support.v7.widget.ActionBarOverlayLayout>
    

    abc_screen_content_include.xml文件内容

    <merge xmlns:android="http://schemas.android.com/apk/res/android">
    
        <android.support.v7.widget.ContentFrameLayout
                android:id="@id/action_bar_activity_content"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:foregroundGravity="fill_horizontal|top"
                android:foreground="?android:attr/windowContentOverlay" />
    </merge>
    

    初始化mDecorContentParent实例

    mDecorContentParent = (DecorContentParent) subDecor
                         .findViewById(R.id.decor_content_parent);
    

    如果mDecorContentParent == null,这初始化mTitleView实例。

    mTitleView = (TextView) subDecor.findViewById(R.id.title);
    

    获取内容View

    final ContentFrameLayout contentView = (ContentFrameLayout) subDecor.findViewById(
                  R.id.action_bar_activity_content);
    

    寻找id为android.R.id.content的布局

    final ViewGroup windowContentView = (ViewGroup) mWindow.findViewById(android.R.id.content);
    

    在findViewById方法中会调用getDecorView方法,如果mDecor == null,这会调用nstallDecor()进行一些必要的初始化操作。

    1. 初始化mDecor(DecorView)
      会创建一个新的DecorView对象

    2. 初始化mContentParent
      内容布局的父容器调用generateLayout方法初始化。

      mContentParent = generateLayout(mDecor);
      

      会根据不同的窗口类型,参数加载不同的布局文件,将布局文件id赋值给layoutResource变量,然后调用DecorView的onResourcesLoaded的方法加载布局文件并添加到mDecor中。

      比如布局文件screen_simple.xml

        <LinearLayout      
              xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="match_parent"
              android:layout_height="match_parent"
              android:fitsSystemWindows="true"
              android:orientation="vertical">
              <ViewStub android:id="@+id/action_mode_bar_stub"
                  android:inflatedId="@+id/action_mode_bar"
                  android:layout="@layout/action_mode_bar"
                  android:layout_width="match_parent"
                  android:layout_height="wrap_content"
                  android:theme="?attr/actionBarTheme" />
              <FrameLayout
                   android:id="@android:id/content"
                   android:layout_width="match_parent"
                   android:layout_height="match_parent"
                   android:foregroundInsidePadding="false"
                   android:foregroundGravity="fill_horizontal|top"
                   android:foreground="?android:attr/windowContentOverlay" />
      </LinearLayout>
      

      找到di为R.id.content容器,然后返回该值并赋值给mContentParent

      ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
      

      从上面分析,windowContentView(即上面id为R.id.content容器实例)此时不为null,那么接下来会把windowContentView里面的子组件全部添加到contentView组件中,同时移除windowContentView该组件,最后将windowContentView组件id清除,并设置contentView组件id为R.id.content。

      调用PhoneWindow的setContentView方法,将传入的contentView添加到mContentParent中,经过前面分析,mContentParent是一个id为View.NO_ID的FrameLayout组件,而contentView是id为R.id.content的ContentFrameLayout组件。

添加自己定义的布局

返回到AppCompatDelegateImpl中的setContentView方法

ViewGroup contentParent = (ViewGroup)mSubDecor.findViewById(android.R.id.content);
contentParent.removeAllViews();
contentParent.addView(v, lp);

找到id为R.id.content容器,移除所以里面存在的子布局,仔细看上面的层级关系,不然这里你以为把ActionBarView等布局都全部移除了。 添加我自己布局到contentParent中。

Android Studio中查看布局层次

如果想观察应用的布局层次,可以Android Studio中查看


截屏2020-03-25上午10.10.40.png

通过上面的分析,得到的视图结构和这张图是完全一致的。

UI绘制

如果想了解UI绘制,那么必须了解一个类ActivityThread,它是程序执行的主入口,在这个类里有一个main函数。Activity的启动也离不开这个类。下面看一下Activity的启动处理。定位到Handler消息处理地方。

public void handleMessage(Message msg) {
   ...
   switch (msg.what) {
      case LAUNCH_ACTIVITY: {
         ...
         handleLaunchActivity(r, null, "LAUNCH_ACTIVITY");
         ...
       }
    }
}

handleLaunchActivity执行了Activity一些初始化操作,创建Activity对象,执行attach,onCreate等生命周期方法。

当handleLaunchActivity执行完,返回Activity实例,然后执行handleResumeActivity方法。在handleResumeActivity回去调用Activity的onResume方法,并设置一些状态值。在handleResumeActivity中看一下这段代码。

if (r.window == null && !a.mFinished && willBeVisible) {
     r.window = r.activity.getWindow();
     View decor = r.window.getDecorView();
     decor.setVisibility(View.INVISIBLE);
     ViewManager wm = a.getWindowManager();
     ...
     wm.addView(decor, l);
 }

跟踪WindowManager的addView方法。得到的是WindowManagerImpl对象,这是WindowManager的实现类。

然后调用WindowManagerGlobal中的addView方法,关于addView方法在WindowManager$BadTokenException(WindowManager源码分析)中仔细分析过。

看一下关键代码,交给ViewRootImpl处理。

root.setView(view, wparams, panelParentView);

如果想仔细了解这个过程,请查看上面给出的链接。

请求布局,调用requestLayout()方法,然后调用scheduleTraversals()方法,然后执行mTraversalRunnable中的run方法。

mChoreographer.postCallback(Choreographer.CALLBACK_TRAVERSAL, mTraversalRunnable, null);

然后调用performTraversals方法

performTraversals()

看一下performTraversals方法中几个重要的方法调用,这个函数代码有点多,自己搜索查找。

  • 通知Activity配置更改
    performConfigurationChange(mPendingMergedConfiguration, !mFirst,INVALID_DISPLAY);
    
  • 执行测量操作
    performMeasure(childWidthMeasureSpec, childHeightMeasureSpec);
    
  • 执行布局操作
    performLayout(lp, mWidth, mHeight);
    
  • 执行画操作
     performDraw();
    

总结

那些接下来就是对这几个方法进行分析了,接下来的几篇文章,都会围绕上面几个方法展开。

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,826评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,968评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,234评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,562评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,611评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,482评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,271评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,166评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,608评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,814评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,926评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,644评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,249评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,866评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,991评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,063评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,871评论 2 354

推荐阅读更多精彩内容