源码打卡第一天
看源码,学习优秀编码技巧,发现方法使用窍门
在Android中,我们经常会用到View.inflate()来动态加载布局。那么,这个方法内部是怎么实现的呢?
让我们来看看源码。看看我们常写的动态加载布局代码:
searchEdtRl= View.inflate(getContext(), R.layout.view_search,this);
1.进入inflate()方法
来自VIew.java
/**
* 从XML资源文件中加载视图。这个便捷方法封装了LayoutInflater类,它为加载视图提供了各种各样的选择
* @param context 上下文.
* @param resource 要被加载的布局资源id
* @param root 一个ViewGroup,上述布局资源Id的父视图,是可选项. 用来加载layoutParams
* @see LayoutInflater
*/
public static View inflate(Context context, @LayoutRes int resource, ViewGroup root) {
LayoutInflater factory = LayoutInflater.from(context);//通过context获取系统加载布局文件的服务,返回LayoutInflater 对象
return factory.inflate(resource, root);//开始加载文件
}
2.进入 return factory.inflate(resource, root);
来自LayoutInflater.java
/**
* 从指定xml文件中加载布局视图。如果发生错误会抛出InflateException异常
* @param resource 布局资源ID,如:R.layout.main_page
* @param root resource视图的父视图,是可选项
* @return 如果提供了root,返回root视图。否则,返回用resource加载出来的视图
*/
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
return inflate(resource, root, root != null);
}
3.进入return inflate(resource, root, root != null);
来自LayoutInflater.java
可以看到,如果用户用的inflate()是两个参数的,如果传了root,resource视图默认添加到root中。
/**
*从指定xml文件中加载布局视图。如果发生错误会抛出InflateException异常。
* @param resource 布局资源ID,如:R.layout.main_page
* @param root resource视图的父视图,是可选项。
* @param attachToRoot 决定resource视图是否会被加到父视图中。如果true:会被加到父视图中。
* false:不会加到父视图中,此时root只是用于为XML中的根视图创建正确的LayoutParams子类。
* @return 如果提供了root 且attachedToToot==true,返回root视图。否则,返回用resource对应xml加载出来的视图
*/
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
final Resources res = getContext().getResources();//获取应用的Resource实例
if (DEBUG) {
Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" ("
+ Integer.toHexString(resource) + ")");
}
final XmlResourceParser parser = res.getLayout(resource);//根据给定的resource资源id获取对应的xml解析器
try {
return inflate(parser, root, attachToRoot);//解析xml结点,加载出每个结点对应的视图
} finally {
parser.close();//关闭xml解析器
}
}
4.进入 return inflate(parser, root, attachToRoot) 。
来自LayoutInflater.java
这是inflate()的核心方法。在这里返回值为result。先把root赋值给result
-->用XmlPullParser循环解析resource指向的xml的各个结点
-->创建xml的根节点视图temp
-->判断root是否为空?否,则生成xml对应的layoutParams
-->判断attachToRoot是否为空?仅把layoutparams设置给temp,且result = temp : 把temp添加到root中,使用layoutParams属性。
/**
*从指定xml文件中加载布局视图。如果发生错误会抛出InflateException异常。
由于性能原因,视图的加载严重依赖编译器对xml文件的预处理。因此,目前不可能在运行时使用xmlPUllParser解析器动态加载xml视图。
* @param parser 包含视图层次结构描述的xml dom结点
* @param root 是可选项。如果attachToRoot==true,则为resource视图的父视图。若attachToRoot==false,则仅用于
为return出去的视图(及resource指向的xml视图)生成layoutParams属性集合。
* @param attachToRoot 决定resource视图是否会被加到父视图中。如果true:会被加到父视图中。
* false:不会加到父视图中,此时root只是用于为XML中的根视图创建正确的LayoutParams子类。
* @return 如果提供了root 且attachedToToot==true,返回root视图。否则,返回用resource对应xml加载出来的视图
*/
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赋值给返回值
try {
// 寻找根节点
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("**************************");
}
//根节点为<merge/>结点单独处理。这里也说明了如果根节点为<merge/>,root必须不能为空,attachToRoot必须为true
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);//调用递归方法遍历xml所有结点并实例化
} else {
// Temp 是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);
}
//如果root不为null,为xml的根视图创建layoutParams属性
params = root.generateLayoutParams(attrs);
//如果attachToRoot==false,仅把params设置给temp
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");
}
// 加载temp中的所有子view视图
rInflateChildren(parser, temp, attrs, true);
if (DEBUG) {
System.out.println("-----> done inflating children");
}
// 把temp及其子view都加到root中,用params属性
if (root != null && attachToRoot) {
root.addView(temp, params);
}
// 如果root是null,或者attachToRoot==false,则返回xml视图。否则,返回传入的root视图,
//当然这个root视图此时已经包含了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;
}
}
5.分析一下第四点中的方法。当根节点是<merge/>结点时加载布局的方法: rInflate(parser, root, inflaterContext, attrs, false);
来自LayoutInflater.java
/**
* 递归方法。解析xml各层级并将所有结点及其子结点实例化为视图。最后调用onFinishInflate()结束。
* 这里得出<include/>结点必须不能为根节点。<merge/>必须为根节点
**/
void rInflate(XmlPullParser parser, View parent, Context context,
AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {
final int depth = parser.getDepth();
int type;
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)) {
parseRequestFocus(parser, parent);//设置是否需要焦点
} else if (TAG_TAG.equals(name)) {
parseViewTag(parser, parent, attrs);//为TAG结点设置key、value标签
} else if (TAG_INCLUDE.equals(name)) {
if (parser.getDepth() == 0) {
throw new InflateException("<include /> cannot be the root element");
}
parseInclude(parser, context, parent, attrs);//如果是遇到include结点,依然会调用rInflate()循环解析结点
} else if (TAG_MERGE.equals(name)) {
throw new InflateException("<merge /> must be the root element");
} else {
final View view = createViewFromTag(parent, name, context, attrs);//根据节点名创建对应View视图对象
final ViewGroup viewGroup = (ViewGroup) parent;
final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);//获取View视图的layoutParams属性集合
rInflateChildren(parser, view, attrs, true);//遍历子节点,依然调用rInflate()循环解析结点
viewGroup.addView(view, params);//把View视图对象加到父视图中,按照params属性。
}
}
if (finishInflate) {
parent.onFinishInflate();
}
}
6.看第5点中的 createViewFromTag(parent, name, context, attrs)方法。
来自LayoutInflater.java
主要有3个流程:
6-1).对view、blinkLayout等特殊标签做处理。* view是小写的
6-2).判断是否设置了factory或者factory2,有则按照对应实现生成view
6-3).如果没有设置factory或者factory2,按照默认的onCreateView方法生成view。
/**
* 这是 createViewFromTag()5参方法的封装。把5参中的ignoreThemeAttr参数置为false。除了include结点外,此方法可用于其他所有结点的解析。
*/
private View createViewFromTag(View parent, String name, Context context, AttributeSet attrs) {
return createViewFromTag(parent, name, context, attrs, false);
}
进入createViewFromTag(parent, name, context, attrs, false)5参方法。介绍了如何把xml的结点加载成为视图对象。
/**
* 用提供的属性集合为对应标签名字创建一个view视图对象。
* @param parent 父视图,用于加载子view的params属性。
* @param name 用来定义view视图对象的xml结点名字
* @param context 上下文
* @param attrs xml结点中用于定义view视图的属性集合
* @param ignoreThemeAttr 是否忽略android:theme属性。
*/
View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
boolean ignoreThemeAttr) {
//解析View标签
if (name.equals("view")) {
name = attrs.getAttributeValue(null, "class");//获取属性的value值.参数1.命名空间。参数2.属性的key值。
}
//如果该标签不忽略主题属性,则把主题信息包装进context的包装类ContextThemeWrapper中
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();
}
//BlinkLayout是一种会一直闪烁的FramLayout,被它包裹的内容会一直闪烁,类似QQ提示信息的那种
if (name.equals(TAG_1995)) {
// Let's party like it's 1995!
return new BlinkLayout(context, attrs);
}
try {
// 设置factory,这是可定制内容,用于对view做额外扩展。
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);
}
//如果此时不存在Factory,不管Factory还是Factory2,还是mPrivateFactory都不存在,那么view就是null。那么直接对name直接进行解析
if (view == null) {
final Object lastContext = mConstructorArgs[0];
mConstructorArgs[0] = context;
try {
//如果name中包含'.'则为自定义控件。否则为原生控件。
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;
}
}
7.调用默认的onCreateView方法生成view
protected View onCreateView(View parent, String name, AttributeSet attrs)
throws ClassNotFoundException {
return onCreateView(name, attrs);
}
/**
* This routine is responsible for creating the correct subclass of View
* given the xml element name. Override it to handle custom view objects. If
* you override this in your subclass be sure to call through to
* super.onCreateView(name) for names you do not recognize.
* 这个方法是真正用来创建view实例的。可以重写这个方法创建自定义view。如果重写,一定要调用super.onCreateView(name)方法
* @param name 要创建的视图的全名
* @param attrs 被创建视图的属性
* @return View 创建好的视图对象
*/
protected View onCreateView(String name, AttributeSet attrs)
throws ClassNotFoundException {
return createView(name, "android.view.", attrs);
}
最终
/**
* 这是根据名字实例化view的低级方法。它试图从LayoutInflater的ClassLoader中找到的指定名称的视图,并将其实例化。
* 会有两种情况发生:1.可能跑出异常,2.可能返回null。前者发生在第一次调用createView()时,后者发生在每次实例化view的时候。
* @param name 要创建的视图的全名
* @param attrs 被创建视图的属性
* @return View 创建好的视图对象
*/
public final View createView(String name, String prefix, AttributeSet attrs)
throws ClassNotFoundException, InflateException {
//从缓存Clazz文件的sConstructorMap集合中取name对应的构造器。若不为空,说明之前加载过这个View对象。清空它
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) {
//通过前缀+name的方式去加载name对应的View实例。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);
//缓存name对应的view实例
sConstructorMap.put(name, constructor);
} else {
//如果有过滤器,用它来判断name对应的View实例是否被允许加载
if (mFilter != null) {
// Have we seen this name before?
Boolean allowedState = mFilterMap.get(name);
if (allowedState == null) {
// New class -- remember whether it is allowed
clazz = mContext.getClassLoader().loadClass(
prefix != null ? (prefix + name) : name).asSubclass(View.class);
boolean allowed = clazz != null && mFilter.onLoadClass(clazz);
//在过滤集合中记录name是否合法。若不被允许加载,抛出name对应的View实例不被允许加载异常
mFilterMap.put(name, allowed);
if (!allowed) {
failNotAllowed(name, prefix, attrs);//抛出name对应的View实例不被允许加载异常
}
} else if (allowedState.equals(Boolean.FALSE)) {
failNotAllowed(name, prefix, attrs);
}
}
}
Object[] args = mConstructorArgs;
args[1] = attrs;
//创建name对应的View实例
final View view = constructor.newInstance(args);
if (view instanceof ViewStub) {
// 如果该实例是ViewStub,则给它设置一个克隆过的LayoutInflater.Use the same context when inflating ViewStub later.
final ViewStub viewStub = (ViewStub) view;
viewStub.setLayoutInflater(cloneInContext((Context) args[0]));
}
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);
}
}
参考链接:http://www.jcodecraeer.com/a/anzhuokaifa/2017/0927/8555.html
网友评论