Android LayoutInflater 原理简析

LayoutInflater Analysis

什么是 LayoutInflater

LayoutInflater 是 Android 的一个类,用来将 xml 文件,转换为对应的 View 对象。

如何创建 LayoutInflater

官方推荐的两种获取 LayoutInflater 实例的方案:

  1. Activity.getLayoutInflater()
  2. Context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)

其中第一种方法,我们分析一下源码

/**
     * Convenience for calling
     * {@link android.view.Window#getLayoutInflater}.
     */
    @NonNull
    public LayoutInflater getLayoutInflater() {
        return getWindow().getLayoutInflater();
    }

可见调用的是 Window.getLayoutInflater,我们知道,Window 的实例其实是 PhoneWindow,因此查看 PhoneWindow 的代码,发现 PhoneWindow 的 LayoutInflater 的创建在这里:

@UnsupportedAppUsage
public PhoneWindow(Context context) {
    super(context);
    mLayoutInflater = LayoutInflater.from(context);
    mRenderShadowsInCompositor = Settings.Global.getInt(context.getContentResolver(),
            DEVELOPMENT_RENDER_SHADOWS_IN_COMPOSITOR, 1) != 0;
}

而 LayoutInflater.from(context) 的实现如下:

/**
 * Obtains the LayoutInflater from the given context.
 */
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;
}

可见殊途同归,最后都是调用 context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) 来获取 LayoutInflater 实例。

不过到这里,我们还是没有找到真正创建 LayoutInflater 的地方,于是继续跟踪 context.getSystemService 方法。
Context 的子类有许许多多,对于 Activity 来说,它继承于 ContextThemeWrapper,于是我们先看 ContextThemeWrapper 的 getSystemService 方法:

@Override
public Object getSystemService(String name) {
    if (LAYOUT_INFLATER_SERVICE.equals(name)) {
        if (mInflater == null) {
            mInflater = LayoutInflater.from(getBaseContext()).cloneInContext(this);
        }
        return mInflater;
    }
    return getBaseContext().getSystemService(name);
}

可以看到这里做了两件事,一是将 BaseContext 的LayoutInflater clone 了一份,而是做了个缓存。
看来要找到真正创建 Inflater 的地方,还得去看这个 BaseContext 的 getSystemService,我们知道,这个getBaseContext,其实最终是返回一个 ContextImpl,于是查看 ContextImpl.getSystemService,发现调用的是 SystemServiceRegistry.getSystemService 方法:

public static Object getSystemService(ContextImpl ctx, String name) {
    if (name == null) {
        return null;
    }
    final ServiceFetcher<?> fetcher = SYSTEM_SERVICE_FETCHERS.get(name);
    if (fetcher == null) {
        if (sEnableServiceNotFoundWtf) {
            Slog.wtf(TAG, "Unknown manager requested: " + name);
        }
        return null;
    }

    // Logs

    return ret;
}

可见是从 SYSTEM_SERVICE_FETCHERS 获取出对应的 Fetcher,然后拿到真正的实例,分析后发现,LayoutInflater 也是注册了一个这样的 Fetcher的:

static {
    // ...
    registerService(Context.LAYOUT_INFLATER_SERVICE, LayoutInflater.class,
            new CachedServiceFetcher<LayoutInflater>() {
        @Override
        public LayoutInflater createService(ContextImpl ctx) {
            return new PhoneLayoutInflater(ctx.getOuterContext());
        }});
    // ...
}

可见创建的是一个 CachedServiceFetcher,作用顾名思义,是做一个缓存,避免重复创建,从这里也可以看出,LayoutInflater 真正的实现类是 PhoneLayoutInflater。

LayoutInflater 原理

LayoutInflater.inflate 时序图

skinparam backgroundColor #999999

actor Caller

Caller -> LI : inflate(int res, ViewGroup parent)
LI -> LI : inflate(int, ViewGroup, boolean)
LI -> Resource : getLayout()
LI -> LI : inflate(XmlParser, ViewGroup, boolean)
LI -> LI : advanceToRootNode()
LI -> LI : createViewFromTag(View parent, String name, Context context, AttributeSet attrs) (root element)
LI -> LI : createViewFromTag(View parent, String name, Context context, AttributeSet attrs, boolean ignoreThemeAttr)
LI -> LI : tryCreateView(@Nullable View parent, @NonNull String name, Context context, AttributeSet attrs)
LI -> Factory2 : onCreateView()
LI -> Factory : onCreateView()
LI -> Factory2 : onCreateView()
LI -> LI : createView(String name, String prefix, AttributeSet attrs)
LI -> LI : createView(@NonNull Context viewContext, @NonNull String name, String prefix, AttributeSet attrs) (Use reflect)
LI -> LI : rInflateChildren(XmlParser, root, attrs, true)
LI --> Caller : View

Factory & Factory2

耗时点

layoutId -> XmlParser

从 LayoutId 到 XmlParser,这里涉及到IO操作

Android resource 加载过程,可参考老罗的博客:
Android应用程序资源的查找过程分析

createView

从 XML Tag,生成 View Object,此处用到反射

BenchMark

Action Time cost (ms)
Inflate a ConstraintLayout 1000 times 104
Inflate a FrameLayout 1000 times 66
Inflate a complex layout 1000 times 1873
Load a complex layout 10 times 2-3

结论:
对于 Heavy 布局:
load 一次耗时 0.2 ms
inflater 一次耗时 1.8ms
可以计算,create view 的耗时大概为 1.6ms,大于 Resource Load 耗时

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容