一年多以前看过源码,感觉了解比较透彻了,长时间不经大脑思考,靠曾经总结的经验使用inflate方法,突然发现不知道什么时候忘记其中的原理了,上网查了一些资料,还各有不同,反而把我搞糊涂了,还是自己看源码来的实在。

inflate有多个重载方法,不过殊途同归,最后的归宿都是下面这个家伙:

   public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {synchronized (mConstructorArgs) {Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");final Context inflaterContext = mContext;final AttributeSet attrs = Xml.asAttributeSet(parser);Context lastContext = (Context) mConstructorArgs[0];mConstructorArgs[0] = inflaterContext;View result = root;try {// Look for the root node.int type;while ((type = parser.next()) != XmlPullParser.START_TAG &&type != XmlPullParser.END_DOCUMENT) {// Empty
                }if (type != XmlPullParser.START_TAG) {throw new InflateException(parser.getPositionDescription()+ ": No start tag found!");}final String name = parser.getName();if (DEBUG) {System.out.println("**************************");System.out.println("Creating root view: "+ name);System.out.println("**************************");}if (TAG_MERGE.equals(name)) {if (root == null || !attachToRoot) {throw new InflateException("<merge /> can be used only with a valid "+ "ViewGroup root and attachToRoot=true");}rInflate(parser, root, inflaterContext, attrs, false);} else {// Temp is the root view that was found in the xmlfinal View temp = createViewFromTag(root, name, inflaterContext, attrs);ViewGroup.LayoutParams params = null;if (root != null) {if (DEBUG) {System.out.println("Creating params from root: " +root);}// Create layout params that match root, if suppliedparams = root.generateLayoutParams(attrs);if (!attachToRoot) {// Set the layout params for temp if we are not// attaching. (If we are, we use addView, below)
                            temp.setLayoutParams(params);}}if (DEBUG) {System.out.println("-----> start inflating children");}// Inflate all children under temp against its context.rInflateChildren(parser, temp, attrs, true);if (DEBUG) {System.out.println("-----> done inflating children");}// We are supposed to attach all the views we found (int temp)// to root. Do that now.if (root != null && attachToRoot) {root.addView(temp, params);}// Decide whether to return the root that was passed in or the// top view found in xml.if (root == null || !attachToRoot) {result = temp;}}} catch (XmlPullParserException e) {InflateException ex = new InflateException(e.getMessage());ex.initCause(e);throw ex;} catch (Exception e) {InflateException ex = new InflateException(parser.getPositionDescription()+ ": " + e.getMessage());ex.initCause(e);throw ex;} finally {// Don't retain static reference on context.mConstructorArgs[0] = lastContext;mConstructorArgs[1] = null;}Trace.traceEnd(Trace.TRACE_TAG_VIEW);return result;}}

1.首先来看看 root!=null && attachToRoot==true的情况:

    if (root != null && attachToRoot) {root.addView(temp, params);}

直接将layout添加至root中,此方法相当于将layout的代码直接放置在root布局的根布局下。

此方法的返回值为root。

2.再看看root!=null && attachToRoot==false的情况:

        if (root != null) {params = root.generateLayoutParams(attrs);if (!attachToRoot) {temp.setLayoutParams(params);}}

此方法返回的值为layout,且layout中设置了自己的layoutParams。

3.最后就是root==null的情况了:

此方法返回的也是layout,与第二种情况不同的是layout中不含layoutParams。

注:与第1中情况不同,第2和第3种情况需自己调用addview方法添加至相应布局中。

总结:

1. root!=null && attachToRoot==true  ----->  将layout完全地添加到root中,返回root。

2. root!=null && attachToRoot==false------>  返回的layout(包含layoutParams)

3. root==nul ------------------------------->  返回layout(不包含layoutParams)

转载于:https://www.cnblogs.com/zhisuoyu/p/5924396.html

Android LayoutInflater.inflate源码解析相关推荐

  1. http://a.codekk.com/detail/Android/grumoon/Volley 源码解析

    http://a.codekk.com/detail/Android/grumoon/Volley 源码解析

  2. BAT高级架构师合力熬夜15天,肝出了这份PDF版《Android百大框架源码解析》,还不快快码住。。。

    前言 为什么要阅读源码? 现在中高级Android岗位面试中,对于各种框架的源码都会刨根问底,从而来判断应试者的业务能力边际所在.但是很多开发者习惯直接搬运,对各种框架的源码都没有过深入研究,在面试时 ...

  3. Android通知系统源码解析

    Android通知系统源码解析 1. 概述 2. 流程图 2.1. 发送通知流程图 3. 源码解析 3.1. 使用通知--APP进程 3.1.1. 创建通知: 3.1.2. 发送(更新)通知: 3.1 ...

  4. Android Gradle Plugin 源码解析(上)

    一.源码依赖 本文基于: android gradle plugin版本: com.android.tools.build:gradle:2.3.0 gradle 版本:4.1 Gradle源码总共3 ...

  5. Android之EasyPermissions源码解析

    转载请标明出处:[顾林海的博客] 个人开发的微信小程序,目前功能是书籍推荐,后续会完善一些新功能,希望大家多多支持! 前言 我们知道在Android中想要申请权限就需要在AndroidManifest ...

  6. Android之AsyncTask源码解析

    转载请标明出处:[顾林海的博客] 个人开发的微信小程序,目前功能是书籍推荐,后续会完善一些新功能,希望大家多多支持! ##前言 AsyncTask是一种轻量级的异步任务类,内部封装了Thread和Ha ...

  7. Android之DiskLruCache源码解析

    转载请标明出处: http://blog.csdn.net/hai_qing_xu_kong/article/details/73863258 本文出自:[顾林海的博客] 个人开发的微信小程序,目前功 ...

  8. Android Hawk的源码解析,一款基于SharedPreferences的存储框架

    转载请标注:http://blog.csdn.net/friendlychen/article/details/76218033 一.概念 SharedPreferences的使用大家应该非常熟悉啦. ...

  9. Android之LocalBroadcastManager源码解析

    转载请标明出处:[顾林海的博客] 个人开发的微信小程序,目前功能是书籍推荐,后续会完善一些新功能,希望大家多多支持! 前言 广播想必大家都不陌生,日常开发中同一个APP中的多个进程之间需要进行传输信息 ...

最新文章

  1. 震惊!ConcurrentHashMap里面也有死循环,作者留下的“彩蛋”了解一下?
  2. shell中符号使用
  3. CentOS 6.6编译安装LAMP(Apache2+PHP+Mysql+PHPmyAdmin)
  4. Qt 可编辑的树模型(Tree Model)的一个实例
  5. java setfilter_Java – setFileFilter问题
  6. 整数线性规划实现(lingo,python分枝界定法)
  7. iostream, istream 和 ostream的区别
  8. hdu2847(2009多校第四场) 01串添加最少01使被k整除(暴力)
  9. Kibana插件sentinl使用教程
  10. 技术文章-Java类的继承
  11. Gym 100342J Triatrip (求三元环的数量) (bitset优化)
  12. 解决办法:nvidia-settings:ERROR: Unable to load info from any available system
  13. eclipse之 Type Hierachy:Viewing the type hierarchy
  14. PHP, 将 PDF/Word/PPT 文档转换成图片生成长图
  15. xp系统itunes无法连接服务器失败,xp系统iTunes无法连接到iTunes store的修复步骤
  16. apache commons fileupload 团队
  17. 纯CSS实现超美选项卡
  18. Unit3D打包android时出错 CommandInvokationFailure: Unable to list target platforms. Please make sure the a
  19. 南柯服务器压力,性能/负载/压力测试 - Mr.南柯 - 51Testing软件测试网 51Testing软件测试网-软件测试人的精神家园...
  20. 是否对纯色背景的IDE感到乏味?那就让vscode背景变成你想要的样子

热门文章

  1. IDEA mybatis 在service无法使用@Autowired , could not autowire
  2. jdbc connection为什么放在webINF的lib里面
  3. WHUST 2015 Summer Contest #11
  4. 重新想象 Windows 8.1 Store Apps (79) - 控件增强: MediaElement, Frame
  5. 用js改变embed标签的src值
  6. 一个用于 Entity Framework 对象拷贝的方法
  7. sqlserver中判断表是否存在
  8. VB.NET 调用外部程序
  9. could not load java7_xml导入properties文件报异常:Could not load JDBC driver class [${jdbc.driver}]...
  10. leetcode算法题--分隔链表