Android Activity的视图结构-装载过程

Android Activity的视图结构-装载过程

目标

1.通过源码得出Android Activity的视图结构

2.了解视图装载过程

handleLaunchActivity

备注:关于Activity的启动过程,我们后面再做分析

Activity的启动都会进去ActivityThread.handleLaunchActivity中

ActivityThread.performLaunchActivity

//创建activity的context实例
ContextImpl appContext = createBaseContextForActivity(r);
//ClassLoader创建当前activity实例
activity = mInstrumentation.newActivity(
                    cl, component.getClassName(), r.intent);
//获取app实例,上面app的创建中已经存在
Application app = r.packageInfo.makeApplication(false, mInstrumentation);

activity.attach(appContext, this, getInstrumentation(), r.token,
                        r.ident, app, r.intent, r.activityInfo, title, r.parent,
                        r.embeddedID, r.lastNonConfigurationInstances, config,
                        r.referrer, r.voiceInteractor, window, r.configCallback,
                        r.assistToken);
//回调activity的onCreate方法                        
mInstrumentation.callActivityOnCreate

performLaunchActivity中

1.创建activity的context实例

2.使用ClassLoader创建当前activity实例

3.makeApplication获取app实例,app的创建中已经存在

4.调用activity.attach方法

5.使用mInstrumentation回调activity的onCreate方法

我们这里重点看activity.attach

Activity.attach

mWindow = new PhoneWindow(this, window, activityConfigCallback);
mWindow.setCallback(this);
mWindowManager = mWindow.getWindowManager();

1.创建了PhoneWindow实例

2.mWindow.getWindowManager最终通过返回 new WindowManagerImpl(mContext, parentWindow)返回WindowManagerImpl实例

setContentView

在onCreate方法回调之后回到我们自定义的Activity中,这里我们需要调用Activity.setContentView,将xml layout资源设置给Activity

那我们接下来看Activity.setContentView

Activity.setContentView

public void setContentView(@LayoutRes int layoutResID) {
    getWindow().setContentView(layoutResID);
    initWindowDecorActionBar();
}

getWindow即为mWindow对象,PhoneWindow实例

initWindowDecorActionBar即为Activity创建ActionBar

顺便可以看Window抽象类的注释,表示仅有一个实现类PhoneWindow

 * <p>The only existing implementation of this abstract class is
 * android.view.PhoneWindow, which you should instantiate when needing a
 * Window.
 */
public abstract class Window

PhoneWindow.setContentView

@Override
public void setContentView(int layoutResID) {
    // Note: FEATURE_CONTENT_TRANSITIONS may be set in the process of installing the window
    // decor, when theme attributes and the like are crystalized. Do not check the feature
    // before this happens.
    if (mContentParent == null) {
        installDecor();
    } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
        mContentParent.removeAllViews();
    }

    if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
        final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
                getContext());
        transitionTo(newScene);
    } else {
        mLayoutInflater.inflate(layoutResID, mContentParent);
    }
    mContentParent.requestApplyInsets();
    final Callback cb = getCallback();
    if (cb != null && !isDestroyed()) {
        cb.onContentChanged();
    }
    mContentParentExplicitlySet = true;
}

installDecor

mDecor = generateDecor(-1);
mContentParent = generateLayout(mDecor);

generateDecor相当于new了一个集成自FrameLayout的DecorView对象

new DecorView(context, featureId, this, getAttributes())

DecorView extends FrameLayout

generateLayout

//初始化PhoneWindow的一些flag和成员属性和decor的属性 动画
//mStatusBarColor mNavigationBarColor
mStatusBarColor = a.getColor(R.styleable.Window_statusBarColor, 0xFF000000);
decor.setSystemUiVisibility
params.windowAnimations


int layoutResource;
//根据不同的features属性(也就是系统的UI风格)加载不同的layout布局
 layoutResource = R.layout.screen_simple;
mDecor.startChanging();
//将layout布局加载到mDecor中
mDecor.onResourcesLoaded(mLayoutInflater, layoutResource);

//用window去寻找R.id.content的viewgroup
ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
//public static final int ID_ANDROID_CONTENT = com.android.internal.R.id.content;
     
mDecor.setWindowBackground(mBackgroundDrawable);

这里可以出generateLayout主要初始化PhoneWindow的一些flag、动画、成员属性,mStatusBarColor、mNavigationBarColor,动画

设置decor的属性(背景),然后去寻找R.id.content的ViewGroup

这里的findViewById其实是调用Window的findViewById,所以最终是在decorView中寻找R.id.content

@Nullable
public <T extends View> T findViewById(@IdRes int id) {
    return getDecorView().findViewById(id);
}

那么他所需要找的id View应该来源于上面onResourcesLoaded的资源,那么我们随便找一个layout看一下,比如R.layout.screen_simple;

主要layout不在SDK的源码包中,需要到framework中查找,当然可以去一些网站搜索文件得到源码,https://www.androidos.net.cn/sourcecode,随便推一个,可得到

<?xml version="1.0" encoding="utf-8"?>
<!--
/* //device/apps/common/assets/res/layout/screen_simple.xml
**
** Copyright 2006, The Android Open Source Project
**
** Licensed under the Apache License, Version 2.0 (the "License"); 
** you may not use this file except in compliance with the License. 
** You may obtain a copy of the License at 
**
**     http://www.apache.org/licenses/LICENSE-2.0 
**
** Unless required by applicable law or agreed to in writing, software 
** distributed under the License is distributed on an "AS IS" BASIS, 
** WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 
** See the License for the specific language governing permissions and 
** limitations under the License.
*/

This is an optimized layout for a screen, with the minimum set of features
enabled.
-->

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

可以看到该布局文件包含了ViewStub和FrameLayout,FrameLayout即为需要找到的R.id.content的组件。

然后我们接着看DecorView的onResourcesLoaded方法干了啥,使用inflater.inflate(layoutResource, null)加载layoutResource,

void onResourcesLoaded(LayoutInflater inflater, int layoutResource) {
    if (mBackdropFrameRenderer != null) {
        loadBackgroundDrawablesIfNeeded();
        mBackdropFrameRenderer.onResourcesLoaded(
                this, mResizingBackgroundDrawable, mCaptionBackgroundDrawable,
                mUserCaptionBackgroundDrawable, getCurrentColor(mStatusColorViewState),
                getCurrentColor(mNavigationColorViewState));
    }

    mDecorCaptionView = createDecorCaptionView(inflater);
    final View root = inflater.inflate(layoutResource, null);
    if (mDecorCaptionView != null) {
        if (mDecorCaptionView.getParent() == null) {
            addView(mDecorCaptionView,
                    new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
        }
        mDecorCaptionView.addView(root,
                new ViewGroup.MarginLayoutParams(MATCH_PARENT, MATCH_PARENT));
    } else {

        // Put it below the color views.
        addView(root, 0, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
    }
    mContentRoot = (ViewGroup) root;
    initializeElevation();
}

那么到这里可以有如下结论:

1.DecorView实质是一个FrameLayout;

2.DecorView会根据不同的features加载一个Framework中的布局文件,该布局文件中包含R.id.content的FrameLayout;

3.mContentParent = generateLayout中,mContentParent 就是R.id.content的FrameLayout

到此installDecor已经全部结束,接着下面mLayoutInflater.inflate(layoutResID, mContentParent)

LayoutInflater.inflate

在installDecor之后,就是将我们自己实现的xml布局文件使用LayoutInflater.inflate,通过解析xml中的view,使用反射创建相应的View,然后递归创建出所有的子View,然后将xml转化后的view add到mContentParent中。

LayoutInflater.inflate的具体过程将不再分析。

StatusBar、NavigationBar

以下内容基于Android29

StatusBar、NavigationBar在DecorView定义,DecorView在onDraw方法中会使用BackgroundFallback将StatusBar和NavigationBar画出。

private final ColorViewState mStatusColorViewState =
        new ColorViewState(STATUS_BAR_COLOR_VIEW_ATTRIBUTES);
private final ColorViewState mNavigationColorViewState =
        new ColorViewState(NAVIGATION_BAR_COLOR_VIEW_ATTRIBUTES);
private static class ColorViewState {
    View view = null;
    int targetVisibility = View.INVISIBLE;
    boolean present = false;
    boolean visible;
    int color;

    final ColorViewAttributes attributes;

    ColorViewState(ColorViewAttributes attributes) {
        this.attributes = attributes;
    }
}
@Override
public void onDraw(Canvas c) {
    super.onDraw(c);

    mBackgroundFallback.draw(this, mContentRoot, c, mWindow.mContentParent,
            mStatusColorViewState.view, mNavigationColorViewState.view);
}

mNavigationColorViewState.view mStatusColorViewState.view的创建是在DecorView的updateColorViewInt中


if (view == null) {
    if (showView) {
        state.view = view = new View(mContext);
        setColor(view, color, dividerColor, verticalBar, seascape);
        view.setTransitionName(state.attributes.transitionName);
        view.setId(state.attributes.id);
        visibilityChanged = true;
        view.setVisibility(INVISIBLE);
        state.targetVisibility = VISIBLE;

        LayoutParams lp = new LayoutParams(resolvedWidth, resolvedHeight,
                resolvedGravity);
        if (seascape) {
            lp.leftMargin = sideMargin;
        } else {
            lp.rightMargin = sideMargin;
        }
        addView(view, lp);
        updateColorViewTranslations();
    }
} 

updateColorViewInt何时调用


1.DecorView实现了WindowCallbacks接口
2.ViewRootImpl持有DecorView的WindowCallbacks实例
3.ViewRootImpl.performTraversals开始绘制时回调onWindowDragResizeStart方法
4.DecorView中的onWindowDragResizeStart调用updateColorViews,绘制StatusBar、NavigationBar

所以StatusBar、NavigationBar是在绘制的时候添加上去的

View的装载过程

image.png

视图结构

image-20210514163642500
image-20210514164027275

参考文章:https://www.jianshu.com/p/7a904184afc6

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

推荐阅读更多精彩内容