LayoutInflater.inflate

LayoutInflater.inflate 这个方法是一个很基础的方法,主要是用来加载一些 xml 布局文件,将其填充为 View 返回。

由于后面 Android 代码写得少了,这个方法具体的参数含义有些模糊,今天重新捋一捋。

/**
 * Inflate a new view hierarchy from the specified xml resource. Throws
 * {@link InflateException} if there is an error.
 *
 * @param resource ID for an XML layout resource to load (e.g.,
 *        <code>R.layout.main_page</code>)
 * @param root Optional view to be the parent of the generated hierarchy (if
 *        <em>attachToRoot</em> is true), or else simply an object that
 *        provides a set of LayoutParams values for root of the returned
 *        hierarchy (if <em>attachToRoot</em> is false.)
 * @param attachToRoot Whether the inflated hierarchy should be attached to
 *        the root parameter? If false, root is only used to create the
 *        correct subclass of LayoutParams for the root view in the XML.
 * @return The root View of the inflated hierarchy. If root was supplied and
 *         attachToRoot is true, this is root; otherwise it is the root of
 *         the inflated XML file.
 */
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)

我们看一下源码里面的注释。

这个方法通过一个指定的 xml 资源,填充出 View 视图。

第一个参数是要进行填充的 xml 文件。

第二个参数是一个可选是参数,并且会根据第三个参数参数不同的效果。
如果第三个参数是 true,则第二个参数将会作为 xml 填充后 View 的父级。如果第三个参数是 false, 则会给 xml 填充后的 View 设置 LayoutParams,其实这里说的 layoutParams 指的就是 xml 里面带 layout_ 开头的属性,这些属性主要是给父组件看的。

第三个参数是决定是否将 xml 填充的 View,添加 root 配置。

这三个参数要联合起来看。其中主要在于后两个参数。

  • 第二个参数为 null ,无论第三个参数传的是什么,最终返回的就只是填充的 xml 布局,并且 xml 布局中根布局的 layout_ 开头的属性都会失效,其实也就是填充出来的 View 没有设置 LayoutParams 。
  • 第二个参数不为空时
    • 第三个参数为 false ,返回的也是返回 xml 布局填充的 View,而且会为这个 View 添加 Layoutparams ,所以 xml 布局中的 layout_ 开头的属性是可以生效的。并且 xml 填充出来的 View 不会添加到 parent 中。
    • 第三个参数为 true ,会将 xml 填充出来到 View 添加到 parent 中,返回到是 parent 。

评论

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×