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,不会出现上面那个坑。.net

相关文章
相关标签/搜索