转载请标明出处: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源代码解析之(十三)--&gt;apk安装流程

    转载请标明出处:一片枫叶的专栏 上一篇文章中给大家分析了一下android系统启动之后调用PackageManagerService服务并解析系统特定文件夹.解析apk文件并安装的过程,这个安装过程实 ...

  2. Android源代码解析之(四)--&gt;HandlerThread

    转载请标明出处:一片枫叶的专栏 上一篇文章中我们解说了AsyncTast的基本使用以及实现原理,我们知道AsyncTask内部是通过线程池和Handler实现的.通过对线程池和handler的封装实现 ...

  3. Android源代码解析之(六)--&gt;Log日志

    转载请标明出处:一片枫叶的专栏 首先说点题外话,对于想学android framework源代码的同学,事实上能够在github中fork一份,详细地址:platform_frameworks_bas ...

  4. Android源代码解析之(三)--&gt;异步任务AsyncTask

    转载请标明出处:一片枫叶的专栏 上一篇文章中我们解说了android中的异步消息机制. 主要解说了Handler对象的使用方式.消息的发送流程等.android的异步消息机制是android中多任务处 ...

  5. Android源代码解析之(七)--&gt;LruCache缓存类

    转载请标明出处:一片枫叶的专栏 android开发过程中常常会用到缓存.如今主流的app中图片等资源的缓存策略通常是分两级.一个是内存级别的缓存,一个是磁盘级别的缓存. 作为android系统的维护者 ...

  6. 《Android源代码设计模式解析》读书笔记——Android中你应该知道的设计模式

    断断续续的,<Android源代码设计模式解析>也看了一遍.书中提到了非常多的设计模式.可是有部分在开发中见到的几率非常小,所以掌握不了也没有太大影响. 我认为这本书的最大价值有两点,一个 ...

  7. 使用具体解释及源代码解析Android中的Adapter、BaseAdapter、ArrayAdapter、SimpleAdapter和SimpleCursorAdapter

    Adapter相当于一个数据源,能够给AdapterView提供数据.并依据数据创建相应的UI.能够通过调用AdapterView的setAdapter方法使得AdapterView将Adapter作 ...

  8. Android EventBus源代码解析 带你深入理解EventBus

    转载请标明出处:http://blog.csdn.net/lmj623565791/article/details/40920453,本文出自:[张鸿洋的博客] 上一篇带大家初步了解了EventBus ...

  9. 《Android源代码设计模式解析与实战》读书笔记(十七)

    第十七章.中介者模式 中介者模式也称为调解者模式或调停者模式,是一种行为型模式. 1.定义 中介者模式包装了一系列对象相互作用的方式.使得这些对象不必相互明显作用.从而使它们能够松散耦合.当某些对象之 ...

随机推荐

  1. C++ 对象的赋值和复制 基本的

    对象的赋值 如果对一个类定义了两个或多个对象,则这些对象之间是可以进行赋值,或者说,一个对象的值可以赋值给另一个同类的对象.这里所指的值是指对象中所有数       据的成员的值.对象之间进行赋值是“ ...

  2. Django day24 cbv和APIView的源码分析 和 resful的规范

    一:cbv的源码分析 1.CBV和FBV的区别: - Class Base View   CBV(基于类的视图) - Function Base View   FBV(基于函数的视图) 2.as_vi ...

  3. BZOJ 4698 差分+后缀数组

    思路: 对所有序列差分一下 公共串的长度+1就是答案了 二分 扫一遍height即可,.. //By SiriusRen #include <cstdio> #include <cs ...

  4. Spring Boot (3) 热部署devtools

    热部署:当发现程序修改时自动启动应用程序. spring boot为开发者提供了一个名为spring-boot-devtools的模块来使sring boot应用支持热部署,提高开发者的开发效率,无需 ...

  5. 前端-git思维导图笔记

    命令汇总 git config配置本地仓库 常用git config --global user.name.git config --global user.email git config --li ...

  6. PHP CURL的几种用法

    1.抓取无访问控制文件 <?php $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, "http://localhost/mytest/ ...

  7. OpenCV:Adaboost训练时数据扩增

    更准确的模型需要更多的数据,对于传统非神经网络机器学习方法,不同的特征需要有各自相符合的数据扩增方法. 1.   在使用opencv_traincascade.exe 过程中,图像读取在 classi ...

  8. 图像局部显著性—点特征(Fast)

    fast作为几乎最快的角点检测算法,一般说明不附带描述子.参考综述:图像的显著性检测--点特征 详细内容,请拜访原=文章:Fast特征点检测算法 在局部特征点检测快速发展的时候,人们对于特征的认识也越 ...

  9. An interesting scroll background------ActionScript3.0

    package { /* *@ ClassName : package::backGround *@ INTRO : the continuously scroll background *@ Aut ...

  10. iOS 加密算法汇总

    CCCryptorStatus CCCryptorCreate( CCOperation op,             /* kCCEncrypt, etc. */ CCAlgorithm alg, ...