inflater.inflate()方法的理解

View inflate(int resource, @Nullable ViewGroup root)

View inflate(int resource, @Nullable ViewGroup root, boolean attachToRoot)

root
Optional view to be the parent of the generated hierarchy (if attachToRoot is true), or else simply an object that provides a set of LayoutParams values for root of the returned hierarchy (if attachToRoot is false.)
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.

看官方解释有点晕。看看源码干了啥。

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

其实View inflate(int resource, @Nullable ViewGroup root)和View inflate(int resource, @Nullable ViewGroup root, boolean attachToRoot)一回事,

// Temp is the root view that was found in the xml
                    final View temp = createViewFromTag(root, name, inflaterContext, attrs);

                    ViewGroup.LayoutParams params = null;

                    if (root != null) {
                        if (DEBUG) {
                            System.out.println("Creating params from root: " +
                                    root);
                        }
                        // Create layout params that match root, if supplied
                        params = root.generateLayoutParams(attrs);
                        if (!attachToRoot) {
                            // Set the layout params for temp if we are not
                            // attaching. (If we are, we use addView, below)
                            temp.setLayoutParams(params);
                        }
                    }

createViewFromTag 函数得到对应resource id产生的view temp,
如果root提供了并且attachToRoot为false,就提取root的布局参数,将该布局参数应用到temp上。

// We are supposed to attach all the views we found (int temp)
                    // to root. Do that now.
                    if (root != null && attachToRoot) {
                        root.addView(temp, params);
                    }

                    // Decide whether to return the root that was passed in or the
                    // top view found in xml.
                    if (root == null || !attachToRoot) {
                        result = temp;
                    }

接着 如果 attachToRoot为true,则将temp直接添加到root中(要求root的父类是ViewGroup)
那么root为空的话 那么就直接返回temp了。

真相大白。

你可能感兴趣的:(inflater.inflate()方法的理解)