Android inflate view的两种方式

Android inflate view的两种方式,View.inflate(Context context, @LayoutRes int resource, ViewGroup root)和LayoutInflater.from(context).inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)。
乍一看这两种方式实现的效果都一样,View.inflate的方法更简洁,那么这两种方式有什么区别吗?
这次要说的重点就在这里,这里面有一个坑,比如在写列表的adapter时,通常要为item的初始化一个view,这时如果用View.inflate的话,是不能填ViewGroup root,得要写null,不然会抛异常:The specified child already has a parent. You must call removeView() on the child's parent first.。这里点开源码我们可以看到,inflate(resource, root, root != null);的第三个参数是否附加于该root,这个参数应该填false。

 public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
        return inflate(resource, root, root != null);
    }

那填了null之后就可以了吗,运行跑起来,有些情况下是view是正常的,但这里有个坑,View.inflate的时候没有填ViewGroup root,item的视图得不到父类view的信息,尺寸可能会有问题,除非item的布局把尺寸写死,不过这样并不好。
这里推荐在初始化view的时候,使用LayoutInflater.from(context).inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)方法,这种传递的信息全面,可以自己填attachToRoot,不会出现上面那个坑。

猜你喜欢

转载自my.oschina.net/u/2606060/blog/1031461