LayoutInflater踩坑日记

   2016-10-10 0
核心提示:Android开发中ayoutInflater还是比较常见的,例如在Adapter或是Fragment中加载Layout布局,拿Adapter来说,在onCreateViewHolder中加载布局然后传给自定义的ViewHolder,通常我们都是这么用的:@Override public CustomViewHolder onCreateViewHolder(ViewGro

Android开发中ayoutInflater还是比较常见的,例如在Adapter或是Fragment中加载Layout布局,拿Adapter来说,在onCreateViewHolder中加载布局然后传给自定义的ViewHolder,通常我们都是这么用的:

@Override
public CustomViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.custom_layout,parent, false);
return new CustomViewHolder(view);
}

这样用是没有问题的,可是如果你不小心将inflate的第二个参数置为null则会有意想不到的事情发生。。。如果你在layout中设置了gravity属性,那么会发现在xml中显示是正常的,但跑起来后就失效了,其实这都是因为inflate的root参数被我们设为了null导致的,接下来,就来看看为什么会出现这个问题。

在Studio中按住CTRL点击inflate去看看源码,首先可以看到我们使用到inflate方法:

public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
final Resources res = getContext().getResources();
if (DEBUG) {
Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" ("
+ Integer.toHexString(resource) + ")");
}

final XmlResourceParser parser = res.getLayout(resource);
try {
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}

在第6行,通过调用Resources的getLayout方法,传入layout的id获取到XmlResourceParser对象,接着是将获得的XmlResourceParser对象传入了另一个inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)方法:

/**
* 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;//将root值赋给result

//解析xml文件
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)) {//根节点是否是merge
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 xml
// 1、创建 root View并将其赋给temp
final 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 supplied
//2、获取到根节点的LayoutParams
params = root.generateLayoutParams(attrs);
if (!attachToRoot) {
// Set the layout params for temp if we are not
// attaching. (If we are, we use addView, below)
//3、如果root!=null并且attachToRoot为false则将获取到的根节点的LayoutParams设置给temp
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.
//4、如果root!=null并且attachToRoot为true则将temp添加到root中
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.
//5、如果root为null或者attachToRoot为false,将temp赋给result
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;
}
}

从上面的注释5中看出:如果将 root 设置为 null,即最后返回的是temp,并没有设置LayoutParams,所以getLayoutParams为null,而ViewGroup在遍历测量子View的时候,会根据自身的MeasureSpec和子View的LayoutParams来创建子View的MeasureSpec,而显然当View的LayoutParams为null会导致测量出错,具体会出现怎么样的效果,和具体的ViewGroup类型有关系。

LayoutInflater相关博客

Hongyang:Android LayoutInflater深度解析 给你带来全新的认识

 
标签: XML 安卓开发
反对 0举报 0 评论 0
 

免责声明:本文仅代表作者个人观点,与乐学笔记(本网)无关。其原创性以及文中陈述文字和内容未经本站证实,对本文以及其中全部或者部分内容、文字的真实性、完整性、及时性本站不作任何保证或承诺,请读者仅作参考,并请自行核实相关内容。
    本网站有部分内容均转载自其它媒体,转载目的在于传递更多信息,并不代表本网赞同其观点和对其真实性负责,若因作品内容、知识产权、版权和其他问题,请及时提供相关证明等材料并与我们留言联系,本网站将在规定时间内给予删除等相关处理.

  • View绘制详解
    View绘制详解
    在介绍View绘制之前先来介绍一下LayoutInflater,而介绍LayoutInflater之前,先介绍一种单例实现模式:使用容器实现单例模式public class SingletonManager {   private static MapString, Object objMap = new HashMapString,Object();  private Singlet
  • Android 中处理 XML 的四种方式-XPath
    适用场景:只取 XML中的部分节点值非常方便,我很喜欢 XPath,关于 XPath语法请参考SelectNodes 与 XPath,这是 C#中的,但是 XPath语法是通用的。import org.xml.sax.InputSource;import java.io.ByteArrayInputStream;import java.io.IOException;import ja
  • Android 中处理 XML 的四种方式-PULL
    PULL和 SAX很相像,都是在节点中走,然后遇到开始节点了、结束节点会触发事件,此时就可以获取值。import org.xmlpull.v1.XmlPullParser;import org.xmlpull.v1.XmlPullParserException;import java.io.ByteArrayInputStream;import java.io.IOException;impo
  • Android 中处理 XML 的四种方式-SAX
    SAX(Simple API for XML)解析速度快,占用内存少。适用为 SAX的场景:映射为对象很方便。流程SAX通过一个 Handler将 XML“映射”到一个对象。XML - Handler - ObjectXML示例?xml version=1.0?rootsiteName千一网络/siteNamesiteUrlhttp://www.cftea.com//si
  • Android 中处理 XML 的四种方式-DOM
    Android 中处理 XML 的几种方式连载中,我们就不介绍合成 XML了,因为合成 XML可以直接拼接字符串,虽然看起很不高大上,但却很有效。我们主要介绍如何取 XML中的值。适用 DOM的场景:只取 XML中的部分节点值方便,但还不如 XPath方便。DOM解析小 XML很快,大
  • 使用FileProvider
    像这样的代码:privatevoidinstall(File apkFile){ Uri uri = Uri.fromFile(apkFile); Intent intent = newIntent(Intent.ACTION_VIEW); intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK); intent.setDataAndType(uri, "application/vnd.android.package-arch
  • 炫酷:一句代码实现标题栏、导航栏滑动隐藏。ByeBurger库的使用和实现
    炫酷:一句代码实现标题栏、导航栏滑动隐藏。By
    其实上周五的时候已经发过一篇文章。基本实现了底部导航栏隐藏的效果。但是使用起来可能不是很实用。因为之前我实现的方式是继承了系统的导航栏,并且提供了响应的隐藏显示方法。这样就变相等于强制使用这个view,体验不是很好。所以抽时间把他优化了一下。因
  • Android - 自定义View冷知识之动态替换layout.x
    在开发迭代中,有这么一个场景:我们给TextView定制了不少功能,在下一个版本,需要把程序中的所有TextView都替换成我自己的CustomTextView,这个时候你会怎么做?有没有一种方法在不改动布局文件的情况下就能实现动态替换呢?原理:layout.xml - Java 对象首
    10-10 安卓开发
  • Gank中的MVP模式
    Gank中的MVP模式
    第一次看到 Gank,还是源于 drakeet 的 Meizhi 项目,后来各种干货项目层出不穷,自己的项目中也借鉴了其中不少的写法,恰好最近公司决定让我做点前端了,同时项目经理也和我一样偏爱 Material Design,在说服了老板后,我就开始边学边用 Materialize 框架重
    10-01 MVC模式XML
  • Android学习笔记---重新学习自定义View#01
    Android学习笔记---重新学习自定义View#01
    最近发现自己对Android的学习只在表面,并没有深入的理解,我不喜欢这种感觉,而且没有自己的理解,学习到的内容也很难为我所用.所以从本次开始,我要写点自己理解的东西,但要对知识有自己的理解,那就必须深入了解它的原理.而我觉得Android的自定义View是一个很好
点击排行