View绘制详解,从LayoutInflater谈起
自定义View算是Android开发中的重中之重了,很多小伙伴可能或多或少都玩过自定义View,对View的绘制流程也有一定的理解。那么现在我想通过几篇博客来详细介绍View的绘制流程,以便使我们更加深刻的理解自定义View。
如果小伙伴们还没用过自定义View或者用的不多的话,那么建议通过以下几篇文章先来热个身:
1.Android自定义View之ProgressBar出场记
3.android自定义View之仿通讯录侧边栏滑动,实现A-Z字母检索
5.自己动手,丰衣足食!一大波各式各样的ImageView来袭!
6.Android开发之Path类使用详解,自绘各种各样的图形!
OK,View的世界浩如烟海,不过凡事只要抓住纲就好解决,所谓提纲挈领嘛。那我这里就打算从LayoutInflater这个布局管理器开始我们的View绘制详解之旅。so,开始吧!
使用LayoutInflater加载一个布局文件,一般情况下,我们通过下面的方式来获取一个LayoutInflater实例:
LayoutInflater inflater = LayoutInflater.from(this);
点到这个方法里边,我们发现这里实际上是调用了系统服务,如下:
public static LayoutInflater from(Context context) {
LayoutInflater LayoutInflater =
(LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (LayoutInflater == null) {
throw new AssertionError("LayoutInflater not found.");
}
return LayoutInflater;
}
看到这里小伙伴们应该明白了,获取LayoutInflater我们还有另外一种方式:
LayoutInflater layoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
两种方式都可以获取一个LayoutInflater实例,拿到实例后,接下来就可以加载布局了,加载布局时我们使用inflate方法,该方法有两个重载的方法,一个是两个参数,一个是三个参数,关于这两个方法的差异小伙伴们如果还不懂可以移步这里三个案例带你看懂LayoutInflater中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 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;
}
}
小伙伴们请看,上面这个方法虽然很长,但是逻辑却很简单,前面几行代码都很简单,就是XML的解析,我们看到Google中布局XML的解析使用了PULL解析的方式,在第24行,首先获取了XML文件根节点的名称,第33行,如果根节点是merge的话,那么要求根节点必须添加到某一个容器中,否则会抛异常(如果小伙伴们对merge这个节点尚不了解,请移步这里android开发之merge结合include优化布局)。如果根节点不是merge,则在第42行通过createViewFromTag方法创建一个View(该方法稍后详述),这个View实际上就是我们要加载布局的根节点,加载到根View之后,加载到根View之后,如果root不为null,则在第52行根据root生成一个LayoutParams,第53行,如果我们设置了不将加载进来的布局加载到root中,即我们传入的attachToRoot为false的话,则将刚刚加载进来的params设置给temp(temp是我们要加载布局的根节点),然后在65行通过rInflateChildren方法开始去读取这个根节点下的所有子控件(该方法稍后详述),第73行,如果我们设置了root不为null,并且要将添加进来的布局加入到root中,则会执行root.addView方法。第79行,如果root为null,则attachToRoot不管是什么都会执行第80行,将temp赋值给result。小伙伴们请注意这个result本身的值就是root。最后将result返回。OK如此看来整个inflate方法思路还是非常清晰的,并没有什么难以理解的地方。接下来我们再来看一看系统是怎么样创建根布局的,以及是怎样创建根布局中的子元素的。首先我们来看看createViewFromTag这个方法。
createViewFromTag这个方法最终会到达这里:
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;
}
}
小伙伴们注意,在这个方法的第40行,首先判断了要实例化的节点的名字中是否包含一个点,包含的话说明该View不是由android.jar提供的,这种情况对应一种解析方式,不包含说明该View是由系统提供的,对应一种解析方式,如果name中不包含点,则最终会调用下面的方法:
protected View onCreateView(String name, AttributeSet attrs)
throws ClassNotFoundException {
return createView(name, "android.view.", attrs);
}
小伙伴们请看,这里系统会自动为View添加上包名,我们再来看看这个createView方法(小伙伴们注意,如果我们的View是自定义View的话,最终也会来到这个方法中):
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?
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);
mFilterMap.put(name, allowed);
if (!allowed) {
failNotAllowed(name, prefix, attrs);
}
} else if (allowedState.equals(Boolean.FALSE)) {
failNotAllowed(name, prefix, attrs);
}
}
} Object[] args = mConstructorArgs;
args[1] = attrs; final View view = constructor.newInstance(args);
if (view instanceof ViewStub) {
// 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);
}
}
这个方法虽然有点长,但是核心目的却很清晰,就是根据View的名称,通过Java中的反射机制来获取一个View实例并返回。OK,以上就是对创建根布局方法createViewFromTag的讲解,其实严格来说,这个方法是创建一个View,我们一会在创建容器中的子View的时候,还会再用到这个方法。OK,现在我们再回到inflate方法的第65行,这里又一个方法叫做rInflateChildren,我们来看看该方法:
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);
} 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 (finishInflate) {
parent.onFinishInflate();
}
}
这个方法倒是很简单,并不长,核心代码就是28行到32行,这里还是调用了上文所说的createViewFromTag方法来获取一个View的实例,然后第31行通过一个递归方法来遍历容器中的所有控件,并将获取到的控件添加到对应的viewGroup中。
OK,以上就是对inflate方法的一个简单解读,整体来说貌似没有什么难点,有问题欢迎留言讨论。
以上。
View绘制详解,从LayoutInflater谈起的更多相关文章
- View绘制详解(二),从setContentView谈起
掐指一算,本来今天该介绍View的测量了,可是要说View的测量,那就要从setContentView谈起了,setContentView本身涉及到的东西也是挺多的,所以今天我们就先来看看这个setC ...
- View绘制详解(五),draw方法细节详解之View的滚动/滑动问题
关于View绘制系列的文章已经完成了四篇了,前面四篇文章主要带小伙伴们熟悉一下View的体系的整体框架.View的测量以及布局等过程,从本篇博客开始,我们就来看看View的绘制过程.View的绘制涉及 ...
- View绘制详解(四),谝一谝layout过程
上篇博客我们介绍了View的测量过程,这只是View显示过程的第一步,第二步就是layout了,这个我们一般译作布局,其实就是在View测量完成之后根据View的大小,将其一个一个摆放在ViewGro ...
- View绘制详解(三),扒一扒View的测量过程
所有东西都是难者不会,会者不难,Android开发中有很多小伙伴觉得自定义View和事件分发或者Binder机制等是难点,其实不然,如果静下心来花点时间把这几个技术点都研究一遍,你会发现其实这些东西都 ...
- SurfaceView 与view区别详解
SurfaceView 与view区别详解 https://blog.csdn.net/u011339364/article/details/83347109 2018年10月24日 17:20:08 ...
- Android游戏开发之旅 View类详解
Android游戏开发之旅 View类详解 自定义 View的常用方法: onFinishInflate() 当View中所有的子控件 均被映射成xml后触发 onMeasure(int, int) ...
- android 开发 View _6_Canvas详解
牛逼大神的博客地址:http://www.gcssloop.com/customview/Canvas_BasicGraphics 安卓自定义View进阶-Canvas之绘制图形 在上一篇自定义Vie ...
- 网页性能管理详解:浅谈chrome-Timeline及window.requestAnimationFrame()方法
你遇到过性能很差的网页吗? 这种网页响应非常缓慢,占用大量的CPU和内存,浏览起来常常有卡顿,页面的动画效果也不流畅. 你会有什么反应?我猜想,大多数用户会关闭这个页面,改为访问其他网站.作为一个开发 ...
- Android中的普通对话框、单选对话框、多选对话框、带Icon的对话框、以及自定义Adapter和自定义View对话框详解
对话框就是一个AlertDialog,但是一个简单的AlertDialog,我们却可以将它玩出许多花样来,下面我们就来一起总结一下AlertDialog的用法.看看各位童鞋在平时的工作中否都用到了Al ...
随机推荐
- java.lang和java.lang.annotation中实现Annotation的类小结
加了注解,等于打上了某种标记,没加,则等于没有某种标记,以后,其他程序可以用反射来了解你的类上面有无何种标记,看你有什么标记,就去干相应的事.标记可以加在类,方法,字段,包上,方法的参数上. (1) ...
- (Android Studio)添加文本框
此文大部分摘自http://hukai.me/android-training-course-in-chinese/basics/firstapp/building-ui.html android : ...
- win7远程链接ubuntu 桌面版
1.安装ubuntu 使用vagrant 添加了一个ubuntu12.04(xmanager好像只能控制最高这个版本,14.04没成功过) 2.安装xmanager 4 3.修改ubutu配置文件 s ...
- 如何查看.Net FrameWork,VC++ 等安装包的启动参数
最近做了一个客户端的程序,客户端程序运行环境要求是.Net FrameWork 4.0 和VC++ 2012 ,在做安装包的时候需要先检测系统环境是否存在这些环境,不存在则安装对应环境. 使用工具来制 ...
- 【译】 AWK教程指南 5AWK中的数组
awk程序中允许使用字符串当做数组的下标(index).利用这个特色十分有助于资料统计工作.(使用字符串当下标的数组称为Associative Array) 首先建立一个数据文件,并取名为 reg.d ...
- CUDA网格限制
如图
- leetcode@ [208] Implement Trie (Prefix Tree)
Trie 树模板 https://leetcode.com/problems/implement-trie-prefix-tree/ class TrieNode { public: char var ...
- jad的用法(反编译某目录下所有class)
jad -s java -d E:\scm\MonitorServerEx\src2 -o -ff -r E:\scm\MonitorServerEx\classes-recomp\**\*.clas ...
- Delphi XE5 安卓手机要求
1 ARMv7 的 CPU v6 的肯定不支持. 2 黑屏是因为你的手机 CPU 不支持 NEON 特性.或者是 T2 海思 CPU .这 2 个不支持. 3 系统版本 2.3.3 到 2.3.9 ...
- 函数 stat() 详解
先看看MSDN的解釋: stat(): Get status information on a file. Parameters: path: pointer to a string con ...