生成布局的时候,经常会用到LayoutInflater.from(context).inflate(layoutRes, parent, false)方法,一直不知其具体实现以及各参数作用,靠猜来实现😂 很惭愧,趁闲暇赶紧补补~
常用到的inflate方式:
- LayoutInflater.from(context).inflate(layoutRes, parent);
- LayoutInflater.from(context).inflate(layoutRes, parent, true/false);
- View.inflate(context, layoutRes, parent);
LayoutInflater.inflate有多个重载的方法,但是最后都调用的是同一个
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)
XmlResourceParser parser = context.getResources().getLayout(layoutRes);
/**
* 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 xml
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
params = 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;
}
}
总结:
- View.inflate(context, layoutRes, root); => LayoutInflater.from(context).inflate(layoutRes, root, root != null);
- inflate(layoutRes, root); => inflate(layoutRes, root, root != null);
- root为空,attachToRoot无意义,返回layoutRes对应的View
- root不为空,attachToRoot为true,则把layoutRes对应的View添加到root中,返回root;attachToRoot为false,则把它的layoutParams设置给layoutRes对应的View,并返回layoutRes对应的View
- merge标签的情况,root不能为空,同时attachToRoot必须为 true,这两个缺一不可,否则会抛出异常
根据xml标签名称生成View,非public方法
View createViewFromTag(View parent, String name, Context context, AttributeSet attrs, boolean ignoreThemeAttr)
/**
* Creates a view from a tag name using the supplied attribute set.
* <p>
* <strong>Note:</strong> Default visibility so the BridgeInflater can
* override it.
*
* @param parent the parent view, used to inflate layout params
* @param name the name of the XML tag used to define the view
* @param context the inflation context for the view, typically the
* {@code parent} or base layout inflater context
* @param attrs the attribute set for the XML tag used to define the view
* @param ignoreThemeAttr {@code true} to ignore the {@code android:theme}
* attribute (if set) for the view being inflated,
* {@code false} otherwise
*/
View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
boolean ignoreThemeAttr) {
if (name.equals("view")) {
name = attrs.getAttributeValue(null, "class");
}
// Apply a theme wrapper, if allowed and one is specified.
if (!ignoreThemeAttr) {
final TypedArray ta = context.obtainStyledAttributes(attrs, ATTRS_THEME);
final int themeResId = ta.getResourceId(0, 0);
if (themeResId != 0) {
context = new ContextThemeWrapper(context, themeResId);
}
ta.recycle();
}
if (name.equals(TAG_1995)) {
// Let's party like it's 1995!
return new BlinkLayout(context, attrs);
}
try {
View view;
if (mFactory2 != null) {
view = mFactory2.onCreateView(parent, name, context, attrs);
} else if (mFactory != null) {
view = mFactory.onCreateView(name, context, attrs);
} else {
view = null;
}
if (view == null && mPrivateFactory != null) {
view = mPrivateFactory.onCreateView(parent, name, context, attrs);
}
if (view == null) {
final Object lastContext = mConstructorArgs[0];
mConstructorArgs[0] = context;
try {
if (-1 == name.indexOf('.')) {
view = onCreateView(parent, name, attrs);
} else {
view = createView(name, null, attrs);
}
} finally {
mConstructorArgs[0] = lastContext;
}
}
return view;
} catch (InflateException e) {
throw e;
} catch (ClassNotFoundException e) {
final InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Error inflating class " + name, e);
ie.setStackTrace(EMPTY_STACK_TRACE);
throw ie;
} catch (Exception e) {
final InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Error inflating class " + name, e);
ie.setStackTrace(EMPTY_STACK_TRACE);
throw ie;
}
}
public interface Factory {
public View onCreateView(String name, Context context, AttributeSet attrs);
}
public interface Factory2 extends Factory {
public View onCreateView(View parent, String name, Context context, AttributeSet attrs);
}
public void setFactory(Factory factory) {
if (mFactorySet) {
throw new IllegalStateException("A factory has already been set on this LayoutInflater");
}
if (factory == null) {
throw new NullPointerException("Given factory can not be null");
}
mFactorySet = true;
if (mFactory == null) {
mFactory = factory;
} else {
mFactory = new FactoryMerger(factory, null, mFactory, mFactory2);
}
}
public void setFactory2(Factory2 factory) {
if (mFactorySet) {
throw new IllegalStateException("A factory has already been set on this LayoutInflater");
}
if (factory == null) {
throw new NullPointerException("Given factory can not be null");
}
mFactorySet = true;
if (mFactory == null) {
mFactory = mFactory2 = factory;
} else {
mFactory = mFactory2 = new FactoryMerger(factory, factory, mFactory, mFactory2);
}
}
/**
* @hide for use by framework
*/
public void setPrivateFactory(Factory2 factory) {
if (mPrivateFactory == null) {
mPrivateFactory = factory;
} else {
mPrivateFactory = new FactoryMerger(factory, factory, mPrivateFactory, mPrivateFactory);
}
}
大概流程:
- 对view标签进行处理,得到新的标签名
<view //注意是小写的view
class="RelativeLayout" //该属性决定view这个节点会变成什么控件,此示例得到的新标签名就是RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
</view>
- 主题相关设置
如果与主题相关,需要将context与theme信息包装至ContextWrapper类。 - 特殊标签返回,blink标签返回BlinkLayout
BlinkLayout其实就是一个FrameLayout,这个控件最后会将包裹内容一直闪烁。
<blink
android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="这个标签会一直闪烁"/>
</blink>
- 依次判断Factory2 mFactory2,Factory mFactory,的状态,调用onCreateView得到view
Factory2和Factory都是一个接口,需要自己实现,它们的区别是Factory2继承自Factory,扩展出一个参数,即该节点的父View;
mFactory2和mFactory只能够设置一次,setFactory2和setFactory方法只能调用其中任意一个一次(两个方法不能都调用,调用的次数只能有一次),且设置的值不能为空,否则会有异常抛出。 - view还为null,且Factory2 mPrivateFactory不为空,调用onCreateView得到view
setPrivateFactory由framework层调用,开发中用不到此方法。需要有一些扩展性操作的话,设置setFactory2或setFactory方法。 - view还为null,调用createView方法得到View
public final View createView(String name, String prefix, AttributeSet attrs)
/**
* Low-level function for instantiating a view by name. This attempts to
* instantiate a view class of the given <var>name</var> found in this
* LayoutInflater's ClassLoader.
*
* <p>
* There are two things that can happen in an error case: either the
* exception describing the error will be thrown, or a null will be
* returned. You must deal with both possibilities -- the former will happen
* the first time createView() is called for a class of a particular name,
* the latter every time there-after for that class name.
*
* @param name The full name of the class to be instantiated.
* @param attrs The XML attributes supplied for this instance.
*
* @return View The newly instantiated view, or null.
*/
public final View createView(String name, String prefix, AttributeSet attrs)
throws ClassNotFoundException, InflateException {
//判断构造器是否已经存在且可用
Constructor<? extends View> constructor = sConstructorMap.get(name);
if (constructor != null && !verifyClassLoader(constructor)) {
constructor = null;
sConstructorMap.remove(name);
}
Class<? extends View> clazz = null;
try {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, name);
//缓存中构造器不存在,即该类还没有被加载过
if (constructor == null) {
// Class not found in the cache, see if it's real, and try to add it
//通过前缀和名称用类加载器加载
clazz = mContext.getClassLoader().loadClass(
prefix != null ? (prefix + name) : name).asSubclass(View.class);
//过滤掉不允许加载的类
if (mFilter != null && clazz != null) {
boolean allowed = mFilter.onLoadClass(clazz);
if (!allowed) {
failNotAllowed(name, prefix, attrs);
}
}
//得到类构造器并缓存起来
constructor = clazz.getConstructor(mConstructorSignature);
constructor.setAccessible(true);
sConstructorMap.put(name, constructor);
} else {
// If we have a filter, apply it to cached constructor
if (mFilter != null) {
// Have we seen this name before?
//有缓存Class是否被允许加载,判断这个Class的过滤状态
Boolean allowedState = mFilterMap.get(name);
//之前没有缓存该类是否可加载
if (allowedState == null) {
// New class -- remember whether it is allowed 不管是否允许,都要重新加载class
clazz = mContext.getClassLoader().loadClass(
prefix != null ? (prefix + name) : name).asSubclass(View.class);
//判断class是否可加载,并缓存结果
boolean allowed = clazz != null && mFilter.onLoadClass(clazz);
mFilterMap.put(name, allowed);
if (!allowed) {
failNotAllowed(name, prefix, attrs);
}
} else if (allowedState.equals(Boolean.FALSE)) {
failNotAllowed(name, prefix, attrs);
}
}
}
Object lastContext = mConstructorArgs[0];
if (mConstructorArgs[0] == null) {
// Fill in the context if not already within inflation.
mConstructorArgs[0] = mContext;
}
Object[] args = mConstructorArgs;
args[1] = attrs;
//过滤通过,实例化该类
final View view = constructor.newInstance(args);
////如果View属于ViewStub那么需要给ViewStub设置一个克隆过的LayoutInflater
if (view instanceof ViewStub) {
// Use the same context when inflating ViewStub later.
final ViewStub viewStub = (ViewStub) view;
viewStub.setLayoutInflater(cloneInContext((Context) args[0]));
}
mConstructorArgs[0] = lastContext;
return view;
} catch (NoSuchMethodException e) {
final InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Error inflating class " + (prefix != null ? (prefix + name) : name), e);
ie.setStackTrace(EMPTY_STACK_TRACE);
throw ie;
} catch (ClassCastException e) {
// If loaded class is not a View subclass
final InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Class is not a View " + (prefix != null ? (prefix + name) : name), e);
ie.setStackTrace(EMPTY_STACK_TRACE);
throw ie;
} catch (ClassNotFoundException e) {
// If loadClass fails, we should propagate the exception.
throw e;
} catch (Exception e) {
final InflateException ie = new InflateException(
attrs.getPositionDescription() + ": Error inflating class "
+ (clazz == null ? "<unknown>" : clazz.getName()), e);
ie.setStackTrace(EMPTY_STACK_TRACE);
throw ie;
} finally {
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
}
总结:通过类加载器实现
void rInflate(XmlPullParser parser, View parent, Context context, AttributeSet attrs, boolean finishInflate)
final void rInflateChildren(XmlPullParser parser, View parent, AttributeSet attrs,
boolean finishInflate) throws XmlPullParserException, IOException {
rInflate(parser, parent, parent.getContext(), attrs, finishInflate);
}
/**
* Recursive method used to descend down the xml hierarchy and instantiate
* views, instantiate their children, and then call onFinishInflate().
* <p>
* <strong>Note:</strong> Default visibility so the BridgeInflater can
* override it.
*/
void rInflate(XmlPullParser parser, View parent, Context context,
AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {
final int depth = parser.getDepth();
int type;
boolean pendingRequestFocus = false;
while (((type = parser.next()) != XmlPullParser.END_TAG ||
parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
if (type != XmlPullParser.START_TAG) {
continue;
}
final String name = parser.getName();
if (TAG_REQUEST_FOCUS.equals(name)) {
pendingRequestFocus = true;
consumeChildElements(parser);
} else if (TAG_TAG.equals(name)) {
parseViewTag(parser, parent, attrs);
} else if (TAG_INCLUDE.equals(name)) {
if (parser.getDepth() == 0) {
throw new InflateException("<include /> cannot be the root element");
}
parseInclude(parser, context, parent, attrs);
} else if (TAG_MERGE.equals(name)) {
throw new InflateException("<merge /> must be the root element");
} else {
final View view = createViewFromTag(parent, name, context, attrs);
final ViewGroup viewGroup = (ViewGroup) parent;
final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
rInflateChildren(parser, view, attrs, true);
viewGroup.addView(view, params);
}
}
if (pendingRequestFocus) {
parent.restoreDefaultFocus();
}
if (finishInflate) {
parent.onFinishInflate();
}
}
rInflate方法是一个递归的方法,会将解析出来的View作为root(父View),继续进行子节点的解析,直到无法解析,即以下情况:
- 当前解析的标识为XmlPullParser.END_TAG(节点结束的标识符),并且深度不在父节点的标签内。
- type 为 XmlPullParser.END_DOCUMENT(文档结束的标识符)。
详细介绍 https://blog.csdn.net/l540675759/article/details/78017065
demo
<FrameLayout>
<LinearLayout>
<TextView />
<ImageView />
</LinearLayout>
</FrameLayout>
补充:
-
XmlPullParser解析器标签
-
START_DOCUMENT:表示解析器在文档的最开始,但尚未读取任何内容。
** 只有在第一次调用next()、nextToken()或nextTag()之前调用getEvent()才能观察此事件类型; -
END_DOCUMENT:XML文档的逻辑结尾。当到达文档的结尾时,从getEventType()、next()和nextToken()返回。
** 在此之后调用到next()和nextToken()可能导致引发异常。 -
START_TAG:当开始标签被读到的时候,从getEventType()、next()和nextToken()返回。
** getName()得到标签的名称;
** getNamespace()得到标签的namespace;
** getPrefix()得到标签的前缀;
** getAttribute()得到元素的属性;
** getDepth()得到元素的深度。在根元素之外,深度为0;当到达开始标记时,深度增加1;在观察到结束标记事件后,深度将减小; -
END_TAG:当结束标签被读到的时候,从getEventType()、next()和nextToken()返回。
由上分析可知,inflate xml文件需要通过耗时的IO操作读取文件内容,再通过反射(类加载器)生成View。所以,在列表中,当 Item 的复用几率很低时,随着 Type 的增多,这种 inflate 带来的损耗是相当大的,此时我们可以用代码去生成布局,即 new View() 的方式。
列表中,每个item已经指定了parent,inflate要选择(layoutRes, parent, false);
setContentView最终调用的也是LayoutInflater.inflate,
framework层会设置对应的Factory2等;
AppCompatActivity extends FragmentActivity extends Activity;
AppCompatActivity.setContentView => AppCompatDelegate.setContentView => LayoutInflater.inflate;
FragmentActivity / Activity.setContentView => PhoneWindow.setContentView => LayoutInflater.inflate;