Android 源码解析 之 setContentView

2023-11-07 18:32

本文主要是介绍Android 源码解析 之 setContentView,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

转载请标明出处: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主界面及消息提醒










           

再分享一下我老师大神的人工智能教程吧。零基础!通俗易懂!风趣幽默!还带黄段子!希望你也加入到我们人工智能的队伍中来!https://blog.csdn.net/jiangjunshow

这篇关于Android 源码解析 之 setContentView的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/365514

相关文章

Android 悬浮窗开发示例((动态权限请求 | 前台服务和通知 | 悬浮窗创建 )

《Android悬浮窗开发示例((动态权限请求|前台服务和通知|悬浮窗创建)》本文介绍了Android悬浮窗的实现效果,包括动态权限请求、前台服务和通知的使用,悬浮窗权限需要动态申请并引导... 目录一、悬浮窗 动态权限请求1、动态请求权限2、悬浮窗权限说明3、检查动态权限4、申请动态权限5、权限设置完毕后

Android里面的Service种类以及启动方式

《Android里面的Service种类以及启动方式》Android中的Service分为前台服务和后台服务,前台服务需要亮身份牌并显示通知,后台服务则有启动方式选择,包括startService和b... 目录一句话总结:一、Service 的两种类型:1. 前台服务(必须亮身份牌)2. 后台服务(偷偷干

C语言中自动与强制转换全解析

《C语言中自动与强制转换全解析》在编写C程序时,类型转换是确保数据正确性和一致性的关键环节,无论是隐式转换还是显式转换,都各有特点和应用场景,本文将详细探讨C语言中的类型转换机制,帮助您更好地理解并在... 目录类型转换的重要性自动类型转换(隐式转换)强制类型转换(显式转换)常见错误与注意事项总结与建议类型

MySQL 缓存机制与架构解析(最新推荐)

《MySQL缓存机制与架构解析(最新推荐)》本文详细介绍了MySQL的缓存机制和整体架构,包括一级缓存(InnoDBBufferPool)和二级缓存(QueryCache),文章还探讨了SQL... 目录一、mysql缓存机制概述二、MySQL整体架构三、SQL查询执行全流程四、MySQL 8.0为何移除查

在Rust中要用Struct和Enum组织数据的原因解析

《在Rust中要用Struct和Enum组织数据的原因解析》在Rust中,Struct和Enum是组织数据的核心工具,Struct用于将相关字段封装为单一实体,便于管理和扩展,Enum用于明确定义所有... 目录为什么在Rust中要用Struct和Enum组织数据?一、使用struct组织数据:将相关字段绑

使用Java实现一个解析CURL脚本小工具

《使用Java实现一个解析CURL脚本小工具》文章介绍了如何使用Java实现一个解析CURL脚本的工具,该工具可以将CURL脚本中的Header解析为KVMap结构,获取URL路径、请求类型,解析UR... 目录使用示例实现原理具体实现CurlParserUtilCurlEntityICurlHandler

深入解析Spring TransactionTemplate 高级用法(示例代码)

《深入解析SpringTransactionTemplate高级用法(示例代码)》TransactionTemplate是Spring框架中一个强大的工具,它允许开发者以编程方式控制事务,通过... 目录1. TransactionTemplate 的核心概念2. 核心接口和类3. TransactionT

数据库使用之union、union all、各种join的用法区别解析

《数据库使用之union、unionall、各种join的用法区别解析》:本文主要介绍SQL中的Union和UnionAll的区别,包括去重与否以及使用时的注意事项,还详细解释了Join关键字,... 目录一、Union 和Union All1、区别:2、注意点:3、具体举例二、Join关键字的区别&php

Android kotlin语言实现删除文件的解决方案

《Androidkotlin语言实现删除文件的解决方案》:本文主要介绍Androidkotlin语言实现删除文件的解决方案,在项目开发过程中,尤其是需要跨平台协作的项目,那么删除用户指定的文件的... 目录一、前言二、适用环境三、模板内容1.权限申请2.Activity中的模板一、前言在项目开发过程中,尤

Spring IOC控制反转的实现解析

《SpringIOC控制反转的实现解析》:本文主要介绍SpringIOC控制反转的实现,IOC是Spring的核心思想之一,它通过将对象的创建、依赖注入和生命周期管理交给容器来实现解耦,使开发者... 目录1. IOC的基本概念1.1 什么是IOC1.2 IOC与DI的关系2. IOC的设计目标3. IOC