android inflate


前言

android中我们经常用到inflate方法,今天对这个方法进行一个总结,inflate方法调用方式如下:

  • View.inflate(Context context, @LayoutRes int resource, ViewGroup root);
  • LayoutInflater.from(Context context).inflate(@LayoutRes int resource, ViewGroup root, boolean attachToRoot);

说白了,一种是通过View类调用其静态方法inflate。另一种是获取LayoutInflater对象,调用LayoutInflater类的inflate方法。

分析

那我们就分别看下这两个方法,首先看下View类的inflate方法。

代码很简单,通过LayoutInflater.from(context);生成一个LayoutInflater对象,调用其inflate方法,传递参数resource,root.

那我们接着看下LayoutInflater中的inflate方法。LayoutInflater中有好几个inflate方法,但是最终调用的都是下边这个方法,所以我们主要分析下边这个方法。

/*** Inflate a new view hierarchy from the specified XML node. Throws* {@link InflateException} if there is an error.* <p>* <em><strong>Important</strong></em>   For performance* reasons, view inflation relies heavily on pre-processing of XML files* that is done at build time. Therefore, it is not currently possible to* use LayoutInflater with an XmlPullParser over a plain XML file at runtime.** @param parser XML dom node containing the description of the view*        hierarchy.* @param root Optional view to be the parent of the generated hierarchy (if*        <em>attachToRoot</em> is true), or else simply an object that*        provides a set of LayoutParams values for root of the returned*        hierarchy (if <em>attachToRoot</em> is false.)* @param attachToRoot Whether the inflated hierarchy should be attached to*        the root parameter? If false, root is only used to create the*        correct subclass of LayoutParams for the root view in the XML.* @return The root View of the inflated hierarchy. If root was supplied and*         attachToRoot is true, this is root; otherwise it is the root of*         the inflated XML file.*/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) {final InflateException ie = new InflateException(e.getMessage(), e);ie.setStackTrace(EMPTY_STACK_TRACE);throw ie;} catch (Exception e) {final InflateException ie = new InflateException(parser.getPositionDescription()+ ": " + e.getMessage(), e);ie.setStackTrace(EMPTY_STACK_TRACE);throw ie;} finally {// Don't retain static reference on context.mConstructorArgs[0] = lastContext;mConstructorArgs[1] = null;Trace.traceEnd(Trace.TRACE_TAG_VIEW);}return result;}}

我们首先看下这几个参数

  • XmlPullParser parser:我们传过来的resourceid被转化成XmlPullParser对象,用于解析布局。
  • ViewGroup root:这个传进的是一个ViewGroup对象,当attachToRoot为true的时候,root就是当前inflate方法返回view的父view,当attachToRoot为false的时候,root就是一个普通的view,用来帮助决定inflate方法返回view的LayoutParams,这块不理解的话,可以看下view的绘制流程,子view的大小是由父view的measurespec和子view的宽高值决定的。
  • boolean attachToRoot,这个就是上边说的,用来决定inflate返回的view跟root是否存在父子布局关系。true表示存在父子关系,系统会将inflate方法返回的view添加到root的子view里。false不添加。

三个参数都明白了,我们在使用inflate方法时,parser参数是保证要传递的,因为我们要新建一个view保证是要有布局支撑的,root可以为null,但是如果为null就代表inflate返回的view没有容器支撑,那么parser布局你写的宽高等数值可能不会起作用,所以必须传一个root容器,attachToRoot当你想创建的view直接为root的子view就设置为true,如果你想创建的view只是需要一个容器,那么就设置attachToRoot为false。

总结

以上基本把LayoutInflater类的inflate方法分析完了。其实View.inflate调用的还是LayoutInflater中的inflate方法,只是attachToRoot的值被默认设置为false,那么说到头来用哪个方法都是一样的,看我们传参的需求,选择最方便的方式即可。

参考:https://blog.csdn.net/u012702547/article/details/52628453#reply

安卓关于inflate方法的总结相关推荐

  1. 带你看懂LayoutInflater中inflate方法

    关于inflate问题,我想很多人多多少少都了解一点,网上也有很多关于这方面介绍的文章,但是枯燥的理论或者翻译让很多小伙伴看完之后还是一脸懵逼,so,我今天想通过三个案例来让小伙伴彻底的搞清楚这个东东 ...

  2. Android之Inflate()方法用途

    flate()作用就是将xml定义的一个布局找出来,但仅仅是找出来而且隐藏的,没有找到的同时并显示功能.最近做的一个项目就是这一点让我迷茫了好几天. Android上还有一个与Inflate()类似功 ...

  3. 三个案例带你看懂LayoutInflater中inflate方法两个参数和三个参数的区别

    本文转载自[http://blog.csdn.net/u012702547/article/details/52628453] 关于inflate参数问题,我想很多人多多少少都了解一点,网上也有很多关 ...

  4. View.inflate和LayoutInflater的inflate方法区别

    平时ListView加载item中,adapter的getView方法中,我们经常用到: LayoutInflater.from(mContext).inflate(R.layout.it ,pare ...

  5. Android之Inflate()方法用途+setContentView和inflate区别

    引用:http://blog.chinaunix.net/uid-27024249-id-3304935.html Android之Inflate()方法用途 Inflate()作用就是将xml定义的 ...

  6. Android inflate方法与 findViewById 方法区别

    在实际开发中LayoutInflater这个类还是非常有用的,它的作用类似于findViewById().不同点是LayoutInflater是用来找res/layout/下的xml布局文件,并且实例 ...

  7. 两个弹窗相互切换(安卓苹果通用方法)

    两个弹窗相互切换(安卓苹果通用方法) 效果 1-点击问号一弹出第一个对话框,第二个对话框消失 2-点击问号二弹出第二个对话框,第一个对话框消失 3-点击其他地方,两个对话框都消失 做法: (1)设置一 ...

  8. inflate简介,LayoutInflater和inflate()方法的用法

    一.inflate简介 inflate这个方法总共有四种形式(见下面),目的都是把xml表述的layout转化为View对象. 其中有一个比较常用,View inflate(int resource, ...

  9. LayoutInflater——inflate方法不同参数的区别

    LayoutInflater有两个参数inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot),inflate(XmlPu ...

  10. 【Android 界面效果43】Android LayoutInflater的inflate方法中attachToRoot的作用

    我们在ListView的Adapter的getView方法里面经常会调用两个参数的inflate方法, mInflater.inflate(R.layout.adv_viewpager, null); ...

最新文章

  1. 算法设计思想(1)— 穷举法
  2. Linux定时备份数据到百度云盘
  3. 详解Shell编程之if语句实战(小结)
  4. 3.1.4 如何使深度学习模型达到人类水平以及超高人类水平
  5. ASP.NET MVC – 关于Action返回结果类型的事儿(上)
  6. 一种基于超体素结合粒子群与模糊聚类实现点云分割的优化算法
  7. 技术债务就像俄罗斯方块,你永远都赢不了!
  8. 曲线绕x轴旋转曲面方程_空间曲线绕空间直线旋转生成的旋转曲面方程
  9. 译: 3. RabbitMQ Spring AMQP 之 Publish/Subscribe 发布和订阅
  10. AngularJS的学习--$on、$emit和$broadcast的使用
  11. html 输入框 相加,JS中,如何实现两个输入框中内容的数字相加?
  12. whitepages 配合调查_“你好,我是警察!请配合我们的调查......”_政务_澎湃新闻...
  13. java开发用win7好还是win10_win10和win7哪个好用|两个系统的性能比较
  14. gpasswd命令简介
  15. 我的世界红石计算机教程1,《我的世界》红石电脑制作原理及使用教程
  16. 【转】解决win10系统每次重启桌面图标排列混乱的问题!亲测有效!!
  17. 户外耳机品牌哪个好、最新的户外耳机品牌排行
  18. BUUCTF-刷题记录-8
  19. C++简单程序典型案例
  20. python 实现自动化

热门文章

  1. crond和crontab详解
  2. 古风一棵桃花树简笔画_唯美意境桃花古风句子
  3. VOT目标路径可视化
  4. Portable Batch System
  5. LSF Command
  6. 子曰:中庸之为德也,其至矣乎!民鲜久矣。
  7. 疫情之下,我们该如何选择工作?
  8. ALPS 2.3.0 安装教程
  9. 物联网产品的平台架构
  10. 权变理论计算机管理理论,现代管理理论的主要学派