从一开始hello world的第一个安卓应用开始,Activity 自动生成,布局自动生成,直接修改布局,在Activity中,findviewById()找到view,然后处理相应的业务逻辑即可,那么setContentView(),是怎么工作的?

~~进入Activity的setContentView源码:

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

  

可以看到里面获取了Window,然后调用了Window的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()

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()方法的实现:

protected DecorView generateDecor() {

return new DecorView(getContext(), -1);

}

public DecorView(Context context, int featureId) {

super(context);

mFeatureId = featureId;  }

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

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的源码继续查看:

有了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中去。

以上转自:http://blog.csdn.net/lmj623565791/article/details/41894125

从当前的activity获得根视图方法:

getWindow().getDecorView().findViewById(android.R.id.content)

getWindow().getDecorView()就是根视图了,当然用Activity.getWindow.getDecorView()来表达意思更为明确。

这里要主要说一下,android.R.id.content,这个ID对应的是什么鬼,这个就是根视图里用来盛放setContentView传入的布局的容器,它是一个线性布局,

(ViewGroup) findViewById(android.R.id.content)可以获得挂在一个activity内容部分LinearLayout。

上图:

这样基本就清楚了,那么官方给出的对应demo的代码,看起来也就不那么奇怪/* * Copyright (C) 2012 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.
*/ package com.example.android.ui; import com.example.android.displayingbitmaps.BuildConfig;
import com.example.android.util.Utils; import android.os.Bundle;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentTransaction; /**
* Simple FragmentActivity to hold the main {@link ImageGridFragment} and not much else.
*/
public class ImageGridActivity extends FragmentActivity {
private static final String TAG = "ImageGridActivity"; @Override
protected void onCreate(Bundle savedInstanceState) {
if (BuildConfig.DEBUG) {
Utils.enableStrictMode();
}
super.onCreate(savedInstanceState); if (getSupportFragmentManager().findFragmentByTag(TAG) == null) {
final FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
ft.add(android.R.id.content, new ImageGridFragment(), TAG);
//不要企图去你自己工程去找上面ID,是系统的
ft.commit();
}
}
}

  

 

Android Activity之 setContentView()总结的更多相关文章

  1. Android Activity的生命周期简单总结

    Android Activity的生命周期简单总结 这里的内容参考官方的文档,这篇文章的目的不是去总结Activity是如何启动,如何创造,以及暂停和销毁的,而是从实际开发中分析在Activity各个 ...

  2. android Activity生命周期(设备旋转、数据恢复等)与启动模式

    1.Activity生命周期     接下来将介绍 Android Activity(四大组件之一) 的生命周期, 包含运行.暂停和停止三种状态,onCreate.onStart.onResume.o ...

  3. Android activity的回传数据

    package com.example.myact3; import android.content.Intent; import android.os.Bundle; import android. ...

  4. Android Activity初探

    原地址:Android Activity初探 Activity是一个应用中的组件,它为用户提供一个可视的界面,方便用户操作,比如说拔打电话.照相.发邮件或者是浏览地图等.每个activity会提供一个 ...

  5. 十九、Android Activity初探

    原文:十九.Android Activity初探 Activity是一个应用中的组件,它为用户提供一个可视的界面,方便用户操作,比如说拔打电话.照相.发邮件或者是浏览地图等.每个activity会提供 ...

  6. xamarin Android activity生命周期详解

    学Xamarin我为什么要写这样一篇关于Android 的activity生命周期的文章 已经学Xamarin android有一段时间了,现在想起当初Xamarin也走了不少的弯路.当然Xamari ...

  7. Android Activity全面解析

    Android Activity全面解析 首先,就从Android四大组件Activity开始. 1.Activity生命周期方法完全解析   activity_lifecycle.png 1).on ...

  8. 4、Android Activity的生命周期 Activity的生命周期

    watermark/2/text/aHR0cDovL2Jsb2cuY3Nkbi5uZXQveXV4aWt1b18x/font/5a6L5L2T/fontsize/400/fill/I0JBQkFCMA ...

  9. Android Activity简介和自定义视图

    ------siwuxie95 Activity简单来说就是一个界面(如桌面也是一个Activity),不同按键对Activity的影响不同(如返回键和Home键) 布局在layout下的activi ...

随机推荐

  1. C#调用WebService实例和开发(转)

    1.1.Web Service基本概念 Web Service也叫XML Web Service WebService是一种可以接收从Internet或者Intranet上的其它系统中传递过来的请求, ...

  2. 垃圾回收器 Dispose 和 Finalize 的互补作用

    假如我们程序有两个窗口 Form1.Form2; 当我们关闭一个窗口的时候,会发出一个 终止响应,并将该窗口对象送入终止队列,公共语言运行库的垃圾回收器跟踪着这个对象的生存期,此时就会调用此对象的基类 ...

  3. MysqlDataSource里的Connection实现类实现了isValid(int timeout)方法

    在项目中,需要连接mysql数据库的时候,我们最好选择使用数据库连接池,即需要选择DataSource. 而在使用c3p0的ComboPooledDataSource时,发现它的Connection实 ...

  4. 解决eclipse无法解析shared_ptr

    今天心血来潮更新了一下机器上的ubuntu,装了14.04版本,原来是32位的,换成64的之后感觉是快了不少(加了内存).因为不少软件没做备份,包括eclipse,所以只得重装,重装之后的麻烦事儿就是 ...

  5. 循环-10. 求序列前N项和*

    /* * Main.c * C10-循环-10. 求序列前N项和 * Created on: 2014年7月30日 * Author: Boomkeeper *******部分通过******* */ ...

  6. ui的设计原则

    部分网页设计原则 规划目录结构时应当遵循的几个原则: 1.不要将所有文件都存放在根目录下; 2.按栏目内容分别建立子目录; 3.在每个主目录下都建立独立的images目录; 4.目录的层次不要太深; ...

  7. java中内存结构及堆栈详解

    一. java内存结构 1. Heap(堆):实例分配的地方,通过-Xms与-Xmx来设置 2. MethodArea(方法区域):类的信息及静态变量. 对应是Permanet Generation, ...

  8. ac命令根据/var/log/wtmp文件登录退出时间计算用户连接时间

    ac命令根据/var/log/wtmp文件登录退出时间计算用户连接时间

  9. aliCloud基于RAMService实现跨账户资源访问

    1,aliCloud基于RAM service实现跨账户ECS资源访问Example 主要的资源为Instance,Image,Snapshot,disk,SecurityGroup Action太多 ...

  10. windows7旗舰版下载出现蓝屏代码50怎么办?

    windows7旗舰版下载出现蓝屏代码50怎么办?电脑蓝屏BCCode:50. 问题事件名称: BlueScreen OS 版本: 6.1.7601.2.1.0.256.1 区域设置 ID: 2052 ...