源码分析之LayoutInflater

学习过程中遇到什么问题或者想获取学习资源的话,欢迎加入Android学习交流群,群号码:364595326  我们一起学Android!

转载自blog.csdn.net/u013356254/article/details/55052363

源码分析之LayoutInflater

简介

基于5.0的framework源码进行分析,通过这篇文章我们能了解:

LayoutInflater的系统级服务的注册过程

inflate填充的过程

ViewStub,merge,include的加载过程

LayoutInflater系统服务的注册过程

我们经常调用

context.getSystemService(Context.LAYOUT_INFLATE_SERVICE)

获得LayoutInflater对象。那么这个对象是什么时候注册到Context中的呢?这个对象的具体实现类是谁?

LayoutInflater这个服务,是在创建Activity的时候,作为baseContext传递给Activity的。接下来我们看源码过程。

我们知道Activity的创建过程是在ApplicationThreadperformLaunchActivity方法中。那么接下来我们分析这个方法

private Activity performLaunchActivity(ActivityClientRecord r, Intent customIntent) {

/*/

Activity activity = null;

try{

// 通过Instrumentation类创建Activity

java.lang.ClassLoader cl = r.packageInfo.getClassLoader();

activity = mInstrumentation.newActivity(

cl, component.getClassName(), r.intent);

}catch(Exeception e){}

/*/

// 创建Context过程,也就是baseContext

Context appContext = createBaseContextForActivity(r, activity);

// 关联activity和baseContext

activity.attach(appContext, this, getInstrumentation(), r.token,

r.ident, app, r.intent, r.activityInfo, title, r.parent,

r.embeddedID, r.lastNonConfigurationInstances, config,

r.referrer, r.voiceInteractor, window);

}

那么接下来我们只要分析

Context appContext = createBaseContextForActivity(r, activity);

这个方法即可,源码继续

private Context createBaseContextForActivity(ActivityClientRecord r, final Activity activity) {

// 通过调用ContextImpl的静态方法创建baseContext对象

ContextImpl appContext = ContextImpl.createActivityContext(

this, r.packageInfo, r.token, displayId, r.overrideConfig);

appContext.setOuterContext(activity);

return baseContext;

}

接下来分析

ContextImpl.createActivityContext(

this, r.packageInfo, r.token, displayId, r.overrideConfig);

appContext.setOuterContext(activity);

接下来我们分析下ContextImpl这个类,发现其有一个成员变量

// 在这里注册系统级别的服务

// The system service cache for the system services that are cached per-ContextImpl.

final Object[] mServiceCache = SystemServiceRegistry.createServiceCache();

SystemServiceRegistry类有个静态代码块,完成了常用服务的注册,代码如下

static{

// 注册LayoutLAYOUT_INFLATER_SERVICE系统服务,具体实现类是PhoneLayoutInflater

registerService(Context.LAYOUT_INFLATER_SERVICE, LayoutInflater.class,

new CachedServiceFetcher() {

@Override

public LayoutInflater createService(ContextImpl ctx) {

return new PhoneLayoutInflater(ctx.getOuterContext());

}});

// 注册AM

registerService(Context.ACTIVITY_SERVICE, ActivityManager.class,

new CachedServiceFetcher() {

@Override

public ActivityManager createService(ContextImpl ctx) {

return new ActivityManager(ctx.getOuterContext(), ctx.mMainThread.getHandler());

}});

// 注册WM

registerService(Context.WINDOW_SERVICE, WindowManager.class,

new CachedServiceFetcher() {

@Override

public WindowManager createService(ContextImpl ctx) {

return new WindowManagerImpl(ctx);

}});

// 等等

}

接下来我们看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 {

// 循环找到第一个view节点,

int type;

while ((type = parser.next()) != XmlPullParser.START_TAG &&

type != XmlPullParser.END_DOCUMENT) {

// Empty

}

// 这里判断是否是第一个view节点

if (type != XmlPullParser.START_TAG) {

throw new InflateException(parser.getPositionDescription()

+ ": No start tag found!");

}

final String name = parser.getName();

// 解析merge标签

if (TAG_MERGE.equals(name)) {

if (root == null || !attachToRoot) {

throw new InflateException(" can be used only with a valid "

+ "ViewGroup root and attachToRoot=true");

}

// 通过rInflate方法将merge标签下的孩子直接合并到root上,这样减少一层布局,达到减少viewTree的目的

rInflate(parser, root, inflaterContext, attrs, false);

} else {

// 调用反射创建view对象

final View temp = createViewFromTag(root, name, inflaterContext, attrs);

ViewGroup.LayoutParams params = null;

if (root != null) {

// Create layout params that match root, if supplied

params = root.generateLayoutParams(attrs);

if (!attachToRoot) {

// 如果view的父容器不为null,并且attachToRoot未true得话,这里只是让刚刚通过反射创建的view使用root(父容器的布局参数)

temp.setLayoutParams(params);

}

}

// 通过深度遍历temp下的节点,之后将节点依次添加到刚刚通过反射创建的temp对象上,因为采用的是深度优先遍历算法,因此viewTree的层级很深的话,会影响遍历的性能

rInflateChildren(parser, temp, attrs, true);

// 判断刚刚创建的temp对象是否添加到父节点上.

// 满足两个条件1 父节点(root)不为null,2 attachToRoot=true

if (root != null && attachToRoot) {

root.addView(temp, params);

}

// 设置result

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) {

} finally {

// Don't retain static reference on context.

mConstructorArgs[0] = lastContext;

mConstructorArgs[1] = null;

Trace.traceEnd(Trace.TRACE_TAG_VIEW);

}

// 返回

return result;

}

}

通过上面分析,我们对inflate的整体过程有了一个了解,也见到了merge标签(经常作为布局文件根节点,来达到减少viewTree的层次)

接下来,我们分析4个方法

rInflate(parser, root, inflaterContext, attrs, false);,其实不管是根节点为merge还是普通的view(最终都会用这个方法),深度遍历添加view

下面是代码

// 深度遍历添加孩子

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)) {

// 如果我们调用了View.setTag(),将会执行下面代码

parseViewTag(parser, parent, attrs);

// include不能作为根节点

} else if (TAG_INCLUDE.equals(name)) {

if (parser.getDepth() == 0) {

throw new InflateException(" cannot be the root element");

}

// 这里解析include标签代码

parseInclude(parser, context, parent, attrs);

} else if (TAG_MERGE.equals(name)) {

// merge一定是根节点

throw new InflateException(" 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最终还会调用rInflate(parser, parent, parent.getContext(), attrs, finishInflate);方法

rInflateChildren(parser, view, attrs, true);

viewGroup.addView(view, params);

}

}

if (finishInflate) {

// viewTree填充完毕,回调自定义view经常使用的onFinishInflate方法

parent.onFinishInflate();

}

}

rInflateChildren(parser, view, attrs, true);方法

// 直接调用rInflate()实现ViewTree

final void rInflateChildren(XmlPullParser parser, View parent, AttributeSet attrs,

boolean finishInflate) throws XmlPullParserException, IOException {

rInflate(parser, parent, parent.getContext(), attrs, finishInflate);

}

createViewFromTag(root, name, inflaterContext, attrs);方法,这个方法其实处理了自定义view和系统view的创建。最终调用了下面方法

View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,

boolean ignoreThemeAttr) {

if (name.equals("view")) {

name = attrs.getAttributeValue(null, "class");

}

// 设置view默认样式

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();

}

try {

View view;

if (view == null) {

final Object lastContext = mConstructorArgs[0];

mConstructorArgs[0] = context;

try {//创建系统view的方法,因为系统view的标签不是完整类名,需要会在 onCreateView中完成拼接(拼接出系统view的完整类名)

if (-1 == name.indexOf('.')) {

view = onCreateView(parent, name, attrs);

} else {

//自定义view的创建

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;

}

}

接下来我们分析 createView(String name, String prefix, AttributeSet attrs)方法,系统view的创建,最终也会调用createView方法。只不过在前面拼接上了系统view的包名。

public final View createView(String name, String prefix, AttributeSet attrs)

throws ClassNotFoundException, InflateException {

// 获取view的构造方法

Constructor constructor = sConstructorMap.get(name);

// 验证

if (constructor != null && !verifyClassLoader(constructor)) {

constructor = null;

sConstructorMap.remove(name);

}

Class clazz = null;

try {

if (constructor == null) {

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);

// 将view的构造方法缓存起来

sConstructorMap.put(name, constructor);

} else {

/*/

}

Object[] args = mConstructorArgs;

args[1] = attrs;

// 反射创建view对象

final View view = constructor.newInstance(args);

// 对viewStub进行处理

if (view instanceof ViewStub) {

// 给ViewStub设置LayoutInfalter.什么时候inflate,什么时候viewStub的内容才显示,(比GONE性能好)

final ViewStub viewStub = (ViewStub) view;

viewStub.setLayoutInflater(cloneInContext((Context) args[0]));

}

return view;

} catch (NoSuchMethodException e) {

} catch (ClassCastException e) {

} catch (ClassNotFoundException e) {

} catch (Exception e) {

} finally {

}

}

总结

系统服务的填充过程,是在ContextImpl中完成注册的

LayoutInflater的实现类是PhoneLayoutInflater

如果仅仅使用父容器的布局参数,可以使用inflater.inflate(layoutId,parent,false);

onFinishInflate()方法是在viewTree遍历完成之后,调用的

merge标签只能是根节点,include标签不能是根节点。

布局优化

view的inflate的过程是深度遍历,因此应该尽量减少viewTree的层次,可以考虑使用merge标签

如果我们不知道view什么时候填充的时候,可以使用ViewStub标签,什么时候用什么时候填充

include是提升复用的

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,015评论 4 362
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,262评论 1 292
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,727评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,986评论 0 205
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,363评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,610评论 1 219
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,871评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,582评论 0 198
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,297评论 1 242
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,551评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,053评论 1 260
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,385评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,035评论 3 236
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,079评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,841评论 0 195
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,648评论 2 274
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,550评论 2 270

推荐阅读更多精彩内容

  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 6,204评论 0 17
  • 用法获取LayoutInflater 首先要注意LayoutInflater本身是一个抽象类,我们不可以直接通过n...
    我本和图阅读 825评论 0 0
  • 有段时间没写博客了,感觉都有些生疏了呢。最近繁忙的工作终于告一段落,又有时间写文章了,接下来还会继续坚持每一周篇的...
    justin_pan阅读 544评论 0 2
  • 1. Java基础部分 基础部分的顺序:基本语法,类相关的语法,内部类的语法,继承相关的语法,异常的语法,线程的语...
    子非鱼_t_阅读 31,293评论 18 399
  • 主产于吉林省延边朝鲜族自治州。圆形边缘里面带有,点状红晕,酷似苹果,故名苹果梨。 延边苹果梨系有1921年从朝鲜引...
    铿锵玫瑰999阅读 1,460评论 0 0