转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/41894125,本文出自:【张鸿洋的博客

大家在平时的开发中,对于setContentView肯定不陌生,那么对其内部的实现会不会比较好奇呢~~~有幸终于能看到一些PhoneWindow神马的源码,今天就带大家来跑一回源码~~

1、Activity  setContentView

首先不用说,进入Activity的setContentView

 public void setContentView(int layoutResID) {
getWindow().setContentView(layoutResID);
initActionBar();
}

可以看到里面获取了Window,然后调用了Window的setContentView

2、PhoneWindow  setContentView

这里的Window的实现类是PhoneWindow(package com.android.internal.policy.impl;),我们直接看它的实现:

 @Override
public void setContentView(int layoutResID) {
if (mContentParent == null) {
installDecor();
} else {
mContentParent.removeAllViews();
}
mLayoutInflater.inflate(layoutResID, mContentParent);
final Callback cb = getCallback();
if (cb != null && !isDestroyed()) {
cb.onContentChanged();
}
}

可以看到,首先判断mContentParent是否为null,是则调用installDecor(),否则移除其内部所有的子Views,然后通过LayoutInflater.inflate将我们传入的layout放置到mContentParent中。

从这里就能看出来mContentParent是个ViewGroup且包裹我们整个布局文件;而installDecor()估计就是去初始化我们这个mContentParent,一会我们会去验证。

接下来,通过getCallBack拿到了一个CallBack对象,其实这个获取到的这个CallBack就是我们Activity自己,你可以去看我们的Activity是实现了CallBack接口的。

这个Callback明显就是一个回调,当PhoneWindow接收到系统分发给它的触摸、IO、菜单等相关的事件时,可以回调相应的Activity进行处理。至于Callback可以回调哪些方法,自己看下这个接口的声明方法即可。当然了这里不是我们的关键,因为我们的setContentView里面只是回调了onContentChanged,而onContentChanged在Activity中是空实现。

好了,接下来去看我们的installDecor()

3、PhoneWindow  installDecor

private void installDecor() {
if (mDecor == null) {
mDecor = generateDecor();
mDecor.setDescendantFocusability(ViewGroup.FOCUS_AFTER_DESCENDANTS);
mDecor.setIsRootNamespace(true);
//...
}
}
if (mContentParent == null) {
mContentParent = generateLayout(mDecor);
mTitleView = (TextView)findViewById(com.android.internal.R.id.title);
if (mTitleView != null) {
//根据FEATURE_NO_TITLE隐藏,或者设置mTitleView的值
//...
} else {
mActionBar = (ActionBarView) findViewById(com.android.internal.R.id.action_bar);
if (mActionBar != null) {
//设置ActionBar标题、图标神马的;根据FEATURE初始化Actionbar的一些显示
//...
}
}
}
}

这里代码比较长,删除了一些初始化Actionbar样式神马的代码。

可以看到这里不仅初始化mContentParent,而且在之前先调用generateDecor();初始化了一个mDecor,mDecor是DecorView对象,为FrameLayout的子类。

在得到mDecor以后设置其焦点的获取方式为,当其子孙都不需要时,自己才获取。

然后通过 generateLayout(mDecor);把mDecor做为参数传入,然后获取到了我们的mContentParent;

接下里就开始通过findViewById进行获取控件了,而这里的findViewById的代码是这样的:

 public View findViewById(int id) {
return getDecorView().findViewById(id);
}

getDecorView返回的就是我们的mDecor。

这里我们猜测下,首先去初始化mDecor,然后通过mDecor初始化了mContentParent,接下来mDecor就可以使用findViewById方法了。那么我觉得,在初始化mDecor的方法

generateDecor()中,一定为我们的mDecor放入了布局或者控件(最简单的就是使用inflate压入了布局文件),而mContentParent可能就是mDecor中的某个子View。

是不是这样呢?

我们一起来先看看generateDecor()方法的实现:

4、PhoneWindow  generateDecor

protected DecorView generateDecor() {
return new DecorView(getContext(), -1);
}
  public DecorView(Context context, int featureId) {
super(context);
mFeatureId = featureId;
}

很遗憾,我们的generateDecor()只是初始化了一个FrameLayout对象,并没有在其内部压入布局文件,看来我们的猜测有些问题;不过没事,既然此方法没有,那么generateLayout(mDecor);中一定设置了layout文件,并且这名字也很像这么回事。

5、PhoneWindow  generateLayout

protected ViewGroup generateLayout(DecorView decor) {
// Apply data from current theme.
TypedArray a = getWindowStyle();
//...Window_windowIsFloating,Window_windowNoTitle,Window_windowActionBar...
//首先通过WindowStyle中设置的各种属性,对Window进行requestFeature或者setFlags if (a.getBoolean(com.android.internal.R.styleable.Window_windowNoTitle, false)) {
requestFeature(FEATURE_NO_TITLE);
}
//...
if (a.getBoolean(com.android.internal.R.styleable.Window_windowFullscreen, false)) {
setFlags(FLAG_FULLSCREEN, FLAG_FULLSCREEN & (~getForcedWindowFlags()));
}
//...根据当前sdk的版本确定是否需要menukey
WindowManager.LayoutParams params = getAttributes();
//通过a中设置的属性,设置 params.softInputMode 软键盘的模式;
//如果当前是浮动Activity,在params中设置FLAG_DIM_BEHIND并记录dimAmount的值。
//以及在params.windowAnimations记录WindowAnimationStyle // Inflate the window decor.
int layoutResource;
int features = getLocalFeatures();
// System.out.println("Features: 0x" + Integer.toHexString(features));
if ((features & ((1 << FEATURE_LEFT_ICON) | (1 << FEATURE_RIGHT_ICON))) != 0) {
if (mIsFloating) {
TypedValue res = new TypedValue();
getContext().getTheme().resolveAttribute(
com.android.internal.R.attr.dialogTitleIconsDecorLayout, res, true);
layoutResource = res.resourceId;
} else {
layoutResource = com.android.internal.R.layout.screen_title_icons;
}
// XXX Remove this once action bar supports these features.
removeFeature(FEATURE_ACTION_BAR);
// System.out.println("Title Icons!");
} else if ((features & ((1 << FEATURE_PROGRESS) | (1 << FEATURE_INDETERMINATE_PROGRESS))) != 0
&& (features & (1 << FEATURE_ACTION_BAR)) == 0) {
// Special case for a window with only a progress bar (and title).
// XXX Need to have a no-title version of embedded windows.
layoutResource = com.android.internal.R.layout.screen_progress;
// System.out.println("Progress!");
} else if ((features & (1 << FEATURE_CUSTOM_TITLE)) != 0) {
// Special case for a window with a custom title.
// If the window is floating, we need a dialog layout
if (mIsFloating) {
TypedValue res = new TypedValue();
getContext().getTheme().resolveAttribute(
com.android.internal.R.attr.dialogCustomTitleDecorLayout, res, true);
layoutResource = res.resourceId;
} else {
layoutResource = com.android.internal.R.layout.screen_custom_title;
}
// XXX Remove this once action bar supports these features.
removeFeature(FEATURE_ACTION_BAR);
} else if ((features & (1 << FEATURE_NO_TITLE)) == 0) {
// If no other features and not embedded, only need a title.
// If the window is floating, we need a dialog layout
if (mIsFloating) {
TypedValue res = new TypedValue();
getContext().getTheme().resolveAttribute(
com.android.internal.R.attr.dialogTitleDecorLayout, res, true);
layoutResource = res.resourceId;
} else if ((features & (1 << FEATURE_ACTION_BAR)) != 0) {
layoutResource = com.android.internal.R.layout.screen_action_bar;
} else {
layoutResource = com.android.internal.R.layout.screen_title;
}
// System.out.println("Title!");
} else if ((features & (1 << FEATURE_ACTION_MODE_OVERLAY)) != 0) {
layoutResource = com.android.internal.R.layout.screen_simple_overlay_action_mode;
} else {
// Embedded, so no decoration is needed.
layoutResource = com.android.internal.R.layout.screen_simple;
// System.out.println("Simple!");
} View in = mLayoutInflater.inflate(layoutResource, null);
decor.addView(in, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT)); ViewGroup contentParent = (ViewGroup)findViewById(ID_ANDROID_CONTENT);
//... return contentParent;
}
}

代码也比较长,首先getWindowStyle在当前的Window的theme中获取我们的Window中定义的属性。具体参考:\frameworks\base\core\res\res\values\attrs.xml

 <!-- The set of attributes that describe a Windows's theme. -->
<declare-styleable name="Window">
<attr name="windowBackground" />
<attr name="windowContentOverlay" />
<attr name="windowFrame" />
<attr name="windowNoTitle" />
<attr name="windowFullscreen" />
<attr name="windowOverscan" />
<attr name="windowIsFloating" />
<attr name="windowIsTranslucent" />
<attr name="windowShowWallpaper" />
<attr name="windowAnimationStyle" />
<attr name="windowSoftInputMode" />
<attr name="windowDisablePreview" />
<attr name="windowNoDisplay" />
<attr name="textColor" />
<attr name="backgroundDimEnabled" />
<attr name="backgroundDimAmount" />

然后就根据这些属性的值,对我们的Window各种requestFeature,setFlags等等。所以这里就是解析我们为Activity设置theme的地方,至于theme一般可以在AndroidManifest里面进行设置。

接下来就到关键的部分了,21-75行:通过对features和mIsFloating的判断,为layoutResource进行赋值,至于值可以为R.layout.screen_custom_title;R.layout.screen_action_bar;等等。至于features,除了theme中设置的,我们也可以在Activity的onCreate的setContentView之前进行requestFeature,也解释了,为什么需要在setContentView前调用requestFeature设置全屏什么的。

得到了layoutResource以后,78行,通过LayoutInflater把布局转化成view,加入到我们的decor,即传入的mDecor中。

接下来81行:通过mDecor.findViewById传入R.id.content(相信这个id大家或多或少都听说过),返回mDecor(布局)中的id为content的View,一般为FrameLayout。

好了,可以看到我们的mDecor是一个FrameLayout,然后会根据theme去选择系统中的布局文件,将布局文件通过inflate转化为view,加入到mDecor中;这些布局文件中都包含一个id为content的FrameLayout,将其引用返回给mContentParent。

等我们的mContentParent有值了以后,还记得干嘛了么?再贴一次PhoneWindow的setContentView

  @Override
public void setContentView(int layoutResID) {
if (mContentParent == null) {
installDecor();
} else {
mContentParent.removeAllViews();
}
mLayoutInflater.inflate(layoutResID, mContentParent);
final Callback cb = getCallback();
if (cb != null && !isDestroyed()) {
cb.onContentChanged();
}
}

有了mContentParent,然后把我们写的布局文件通过inflater加入到mContentParent中。

关于R.layout.xxx可以在frameworks\base\core\res\res\layout里面进行查看。

例如:R.layout.screen_custom_title.xml

<?xml version="1.0" encoding="utf-8"?>

<!--
This is a custom layout for a screen.
--> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:fitsSystemWindows="true">
<!-- Popout bar for action modes -->
<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" /> <FrameLayout android:id="@android:id/title_container"
android:layout_width="match_parent"
android:layout_height="?android:attr/windowTitleSize"
style="?android:attr/windowTitleBackgroundStyle">
</FrameLayout>
<FrameLayout android:id="@android:id/content"
android:layout_width="match_parent"
android:layout_height="0dip"
android:layout_weight="1"
android:foregroundGravity="fill_horizontal|top"
android:foreground="?android:attr/windowContentOverlay" />
</LinearLayout>

上面的title_container是用来放自定义Title的容器,而下面的content就是放置我们设置的布局的容器。关于自定义Title例子,大家可以百度下。

到此,我们的setContentView就分析完成了,我们可以回顾一下:

首先初始化mDecor,即DecorView为FrameLayout的子类。就是我们整个窗口的根视图了。

然后,根据theme中的属性值,选择合适的布局,通过infalter.inflater放入到我们的mDecor中。

在这些布局中,一般会包含ActionBar,Title,和一个id为content的FrameLayout。

最后,我们在Activity中设置的布局,会通过infalter.inflater压入到我们的id为content的FrameLayout中去。

----------------------------------------------------------------------------------------------------------

博主部分视频已经上线,如果你不喜欢枯燥的文本,请猛戳(初录,期待您的支持):

1、Android 自定义控件实战 电商活动中的刮刮卡

2、Android自定义控件实战  打造Android流式布局和热门标签

3、Android智能机器人“小慕”的实现

4、高仿QQ5.0侧滑

5、高仿微信5.2.1主界面及消息提醒

版权声明:本文为博主原创文章,未经博主允许不得转载。

Android 源码解析 之 setContentView的更多相关文章

  1. android源码解析(十七)-->Activity布局加载流程

    版权声明:本文为博主原创文章,未经博主允许不得转载. 好吧,终于要开始讲讲Activity的布局加载流程了,大家都知道在Android体系中Activity扮演了一个界面展示的角色,这也是它与andr ...

  2. Android源码解析系列

    转载请标明出处:一片枫叶的专栏 知乎上看了一篇非常不错的博文:有没有必要阅读Android源码 看完之后痛定思过,平时所学往往是知其然然不知其所以然,所以为了更好的深入Android体系,决定学习an ...

  3. Android源码解析——LruCache

    我认为在写涉及到数据结构或算法的实现类的源码解析博客时,不应该急于讲它的使用或马上展开对源码的解析,而是要先交待一下这个数据结构或算法的资料,了解它的设计,再从它的设计出发去讲如何实现,最后从实现的角 ...

  4. Android源码解析——Toast

    简介 Toast是一种向用户快速展示少量信息的视图.当它显示时,它会浮在整个应用层的上面,并且不会获取到焦点.它的设计思想是能够向用户展示些信息,但又能尽量不显得唐突.本篇我们来研读一下Toast的源 ...

  5. Android源码解析——AsyncTask

    简介 AsyncTask 在Android API 3引入,是为了使UI线程能被正确和容易地使用.它允许你在后台进行一些操作,并且把结果带到UI线程中,而不用自己去操纵Thread或Handler.它 ...

  6. Android源码解析——Handler、Looper与MessageQueue

    本文的目的是来分析下 Android 系统中以 Handler.Looper.MessageQueue 组成的异步消息处理机制,通过源码来了解整个消息处理流程的走向以及相关三者之间的关系 需要先了解以 ...

  7. Android 源码解析之AsyncTask

    AsyncTask相信大家都不陌生,它是为了简化异步请求.更新UI操作而诞生的.使用它不仅可以完成我们的网络耗时操作,而且还可以在完成耗时操作后直接的更新我们所需要的UI组件.这使得它在android ...

  8. 【Android源码解析】View.post()到底干了啥

    emmm,大伙都知道,子线程是不能进行 UI 操作的,或者很多场景下,一些操作需要延迟执行,这些都可以通过 Handler 来解决.但说实话,实在是太懒了,总感觉写 Handler 太麻烦了,一不小心 ...

  9. Android 源码解析:单例模式-通过容器实现单例模式-懒加载方式

    本文分析了 Android 系统服务通过容器实现单例,确保系统服务的全局唯一. 开发过 Android 的用户肯定都用过这句代码,主要作用是把布局文件 XML 加载到系统中,转换为 Android 的 ...

随机推荐

  1. HBase 索引创建

    本文参考了文"mysql索引背后的数据结构及算法原理",之所以还要摘录,主要是为了形成hbase索引研究的开篇,弄明白什么索引的本质,如有版权问题,请及时通知. 索引的本质 索引是 ...

  2. MyBatis 框架之快速入门程序

    一.使用 IDEA 快速创建 Maven 项目 关于如何快速创建 Maven 项目,这个可以参考下面这篇文章: Maven 项目管理工具基础入门系列(一) 二.快速配置 MyBatis 依赖 jar ...

  3. 北京一家JAVA开发公司面试题(留给后人)

    1.jsp有哪些内置对象?作用分别是什么? 2.描述一下servlet的生命周期和基本架构. 3.多线程有几种实现方法,都是什么? 同步有几种实现方法,都是什么? 4.作用域public   priv ...

  4. 远离压力,提高效率——Getting things done读书笔记

    一.确定时间.空间和工具   二.收集阶段:填充工作篮         1. 这有助于你认识到自己面对的工用量.         2. 同时让你清楚"隧道的终点"在哪        ...

  5. JVM-GC工作原理

     配置Garbage Collection 2012-09-17 14:53:18 分类: Java   上面这幅图是我从网络上摘到的,它展现了在一个的理想系统的模型下GC对系统的影响.图的最顶上红色 ...

  6. datetimepicker日期框选择后,无法触发bootstrapValidator

    如上图所示,当选择日期后下面的"栏位不能为空"提示并不能及时的消失,同时点击提交按钮也没有用. 解决如下: 在birthday的校验规则里面添加trigger:'change',就 ...

  7. Day24 中间件 自定义分页 ModelForm 序列化 缓存 信号

    在views里边,怎么导入局部配置和全局配置 from s18day24 import settings #这样导入的是仅仅用户自定义的配置 from django.conf import setti ...

  8. Day 网络协议介绍 简单通信的实现

    比如说实现两个手机之间的通信,需要做的几部: 服务端: 1,买手机 2,插卡 3,开机 4,等电话链接 5,基于建立的链接,收发协议 6,挂电话 7,关机 import socket #买手机 pho ...

  9. Windows 10创意者更新ISO发布!官方下载

    http://news.mydrivers.com/1/526/526719.htm 去年7月份,微软面向Windows 10推出了“周年更新”,让系统变得更加稳定好用.今天,Windows 10迎来 ...

  10. Sublime text 3 注册码激活码 版本号3143

    —– BEGIN LICENSE —– TwitterInc 200 User License EA7E-890007 1D77F72E 390CDD93 4DCBA022 FAF60790 61AA ...