LayoutInflater 类似 HTML转换成DOM?

/**
 * Instantiates a layout XML file into its corresponding {@link android.view.View}
 * objects. It is never used directly. Instead, use
 * {@link android.app.Activity#getLayoutInflater()} or
 * {@link Context#getSystemService} to retrieve a standard LayoutInflater instance
 * that is already hooked up to the current context and correctly configured
 * for the device you are running on.
 * <p>
 * To create a new LayoutInflater with an additional {@link Factory} for your
 * own views, you can use {@link #cloneInContext} to clone an existing
 * ViewFactory, and then call {@link #setFactory} on it to include your
 * Factory.
 * <p>
 * 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;
 * it only works with an XmlPullParser returned from a compiled resource
 * (R.<em>something</em> file.)
 * <p>
 * <strong>Note:</strong> This class is <strong>not</strong> thread-safe and a given
 * instance should only be accessed by a single thread.

好的,我来帮你翻译并总结一下这段
LayoutInflater
的官方注释


翻译

作用

LayoutInflater
的作用是:把一个 布局 XML 文件 转换成对应的
View
对象树。

使用方式
一般不要直接用它,而是通过:


Activity.getLayoutInflater()


Context.getSystemService(Context.LAYOUT_INFLATER_SERVICE)

来获取一个已经绑定当前
Context
并配置好的
LayoutInflater
实例。

扩展
如果你想要在解析布局时 插入自己的 View 工厂(比如自定义控件的构造逻辑),可以用
cloneInContext
克隆一个已有的
LayoutInflater
,然后调用
setFactory
来加入自己的工厂。

性能原因
为了性能,
LayoutInflater
依赖于编译期对 XML 文件的预处理。
👉 这意味着它 不能 直接用一个普通的
XmlPullParser
去解析“纯 XML 文件”(比如你自己在运行时读的
.xml
),只能解析 编译后的资源文件(也就是
R.layout.xxx
这样的)。

线程安全
这个类 不是线程安全的,所以一个
LayoutInflater
实例只能在 单线程 下使用。


总结

作用:把 XML 布局转成
View

获取方式:用
Activity.getLayoutInflater()

Context.getSystemService()
,不要自己 new。

扩展性:可以通过
cloneInContext + setFactory
来支持自定义 View 的创建逻辑。

限制:只能解析 编译后的布局资源,不能解析纯 XML 文件。

注意:不是线程安全的,只能在一个线程里用。


© 版权声明
THE END
如果内容对您有所帮助,就支持一下吧!
点赞0 分享
评论 抢沙发

请登录后发表评论

    暂无评论内容