美文网首页
LayoutInflater 调用 inflate 方法 和 V

LayoutInflater 调用 inflate 方法 和 V

作者: primopeng | 来源:发表于2016-08-02 16:49 被阅读0次

    LayoutInflater 和 view 都可以调用inflate()方法来加载布局文件。但是他们之间有什么区别吗?

    我们打开View的inflate方法会看到如下代码:

    图一

    咋一看,和我们平时使用的

    图二

    没又太大区别。我们接着打开View中的inflate方法中的factory.inflate()

    方法,如下:

    图三

    我们看用红线框标出的参数,可以这么理解,如果传入的根View不为空的话,那加载的布局文件将添加到该root View中(inflate的第三个参数为是否 attach to root)。那看到的人就会问,那又怎么了。如果用同一个root去加载多个布局文件或者多次加载同一个布局文件就会有问题了。如果你用View中的inflate的方法,用同一个parent去多次加载布局文件,将会得到这样的错误,IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.那么你又会问用LayoutInflater中的inflate方法为什么不会有这样的问题,那时因为LayoutInflater中的inflate方法在传入parent view的时间可以指定,是否attach 到parent view上(如图二所示)。然而View的inflate方法,如果传入parent view就一定要附加到parent view视图中。

    相关文章

      网友评论

          本文标题:LayoutInflater 调用 inflate 方法 和 V

          本文链接:https://www.haomeiwen.com/subject/trsijttx.html