LayoutInflater想必对于Android开发者来说都不陌生,它主要用于加载布局,在Fragment的onCreateView方法、ListView Adapter的getView方法等许多地方都可以见到它的身影,它也就是将 文件转换成一个View供我们使用。那么它是怎么将 文件转成View的尼?带着这个疑问往下看。

LayoutInflater的使用

 LayoutInflater是一个抽象类,所以我们无法直接通过new来创建LayoutInflater对象,但系统给我们提供了如下几种方式来获取LayoutInflater对象。

  1. LayoutInflater.from(context)
  2. 在Activity内部调用getLayoutInflater()方法
  3. LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

 前面两种方式最终都是调用的第三种方式context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);,它返回的是一个继承自LayoutInflater的类——PhoneLayoutInflater,这个类很简单,主要是重写了onCreateViewcloneInContext这两个方法。代码如下:

public class PhoneLayoutInflater extends LayoutInflater {
    private static final String[] sClassPrefixList = {
        \"android.widget.\",
        \"android.webkit.\",
        \"android.app.\"
    };

    /**
     * Instead of instantiating directly, you should retrieve an instance
     * through {@  Context#getSystemService}
     *
     * @param context The Context in which in which to find resources and other
     *                application-specific things.
     *
     * @see Context#getSystemService
     */
    public PhoneLayoutInflater(Context context) {
        super(context);
    }

    protected PhoneLayoutInflater(LayoutInflater original, Context newContext) {
        super(original, newContext);
    }

    /** Override onCreateView to instantiate names that correspond to the
        widgets known to the Widget factory. If we don\'t find a match,
        call through to our super class.
    */
    @Override protected View onCreateView(String name, AttributeSet attrs) throws ClassNotFoundException {
        for (String prefix : sClassPrefixList) {
            try {
                //如果是android.widget、android.webkit、android.app这三个包下的控件,则直接调用createView
                View view = createView(name, prefix, attrs);
                if (view != null) {
                    return view;
                }
            } catch (ClassNotFoundException e) {
                // In this case we want to let the   class take a crack
                // at it.
            }
        }

        return super.onCreateView(name, attrs);
    }

    public LayoutInflater cloneInContext(Context newContext) {
        return new PhoneLayoutInflater(this, newContext);
    }
}

 拿到PhoneLayoutInflater对象后就能够调用inflate来加载布局,由于PhoneLayoutInflater并没有重写inflate这个方法,所以还是调用的LayoutInflater里面的inflate方法,inflate有多个不同的重载方法。代码如下:

//方法一
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) 
//方法二
public View inflate( PullParser parser, @Nullable ViewGroup root)
//方法三
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot)
//方法四
public View inflate( PullParser parser, @Nullable ViewGroup root, boolean attachToRoot)

 方法一跟方法三想必大家都很熟悉,但它们的最终都是调用了都是方法四。

LayoutInflater源码分析

 前面说了加载布局的最终实现是方法四,但方法四具体是怎么来实现的尼?先来看一下代码。

    public View inflate( PullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
        synchronized (mConstructorArgs) {
            Trace.traceBegin(Trace.TRACE_TAG_VIEW, \"inflate\");

            final Context inflaterContext = mContext;
            final AttributeSet attrs =  .asAttributeSet(parser);
            Context lastContext = (Context) mConstructorArgs[0];
            mConstructorArgs[0] = inflaterContext;
            View result = root;

            try {
                // Look for the root node.
                int type;
                //找到根节点
                while ((type = parser.next()) !=  PullParser.START_TAG &&
                        type !=  PullParser.END_DOCUMENT) {
                    // Empty
                }
                //没有拿到根节点
                if (type !=  PullParser.START_TAG) {
                    throw new InflateException(parser.getPositionDe ion()
                            + \": No start tag found!\");
                }
                //拿到根节点的名称,如果是LinearLayout则name为LinearLayout
                final String name = parser.getName();
                //如果根节点是merge
                if (TAG_MERGE.equals(name)) {
                    //如果根节点是merge且不附加到任何View上则会抛异常
                    if (root == null || !attachToRoot) {
                        throw new InflateException(\"<merge /> can be used only with a valid \"
                                + \"ViewGroup root and attachToRoot=true\");
                    }
                    //开始解析布局并创建View对象
                    rInflate(parser, root, inflaterContext, attrs, false);
                } else {
                    // Temp is the root view that was found in the  
                    //创建View对象,通过反射创建的
                    final View temp = createViewFromTag(root, name, inflaterContext, attrs);

                    ViewGroup.LayoutParams params = null;

                    if (root != null) {
                        
                        // 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);
                        }
                    }
                    // Inflate all children under temp against its context.
                    //解析并创建所有的子View
                    rInflateChildren(parser, temp, attrs, true);
                    // We are supposed to attach all the views we found (int temp)
                    // to root. Do that now.
                    //直接添加到父View中,这时候外面就不能在调用root.addView了,否则抛异常
                    if (root != null && attachToRoot) {
                        root.addView(temp, params);
                    }

                    // Decide whether to return the root that was passed in or the
                    // top view found in  .
                    //直接返回生成的View对象
                    if (root == null || !attachToRoot) {
                        result = temp;
                    }
                }

            } catch ( PullParserException e) {
               ...
            }

            return result;
        }
    }

 代码也比较简单,首先就是解析 文件。常用的 解析方式有DOM,SAX和PULL三种方式。DOM不适合 文档较大,内存较小的场景,所以不适用于手机这样内存有限的移动设备上。SAX和PULL类似,都具有解析速度快,占用内存少的优点,而相对之下,PULL的操作方式更为简单易用,所以,Android系统内部在解析各种 时都用的是PULL解析器。然后拿到根节点,如果根节点为merge且满足root == null || !attachToRoot这个条件就会抛异常,否则就去遍历所有子节点并创建View对象。

    void rInflate( PullParser parser, View parent, Context context,
            AttributeSet attrs, boolean finishInflate) throws  PullParserException, IOException {

        final int depth = parser.getDepth();
        int type;
        boolean pendingRequestFocus = false;

        while (((type = parser.next()) !=  PullParser.END_TAG ||
                parser.getDepth() > depth) && type !=  PullParser.END_DOCUMENT) {

            if (type !=  PullParser.START_TAG) {
                continue;
            }

            final String name = parser.getName();
            //获取焦点
            if (TAG_REQUEST_FOCUS.equals(name)) {
                pendingRequestFocus = true;
                consumeChildElements(parser);
            //如果是Tag标签
            } else if (TAG_TAG.equals(name)) {
                parseViewTag(parser, parent, attrs);
            //如果是include标签
            } else if (TAG_INCLUDE.equals(name)) {
                if (parser.getDepth() == 0) {
                    throw new InflateException(\"<include /> cannot be the root element\");
                }
                parseInclude(parser, context, parent, attrs);
            //如果是merge标签
            } else if (TAG_MERGE.equals(name)) {
                throw new InflateException(\"<merge /> must be the root element\");
            } else {
                //创建View对象
                final View view = createViewFromTag(parent, name, context, attrs);
                final ViewGroup viewGroup = (ViewGroup) parent;
                final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
                rInflateChildren(parser, view, attrs, true);
                //添加到父View
                viewGroup.addView(view, params);
            }
        }

        if (pendingRequestFocus) {
            parent.restoreDefaultFocus();
        }

        if (finishInflate) {
            parent. Inflate();
        }
    }

 如果根节点不是merge,则创建根对象,然后遍历所有子节点并创建对象。遍历子节点代码如下:

    final void rInflateChildren( PullParser parser, View parent, AttributeSet attrs,
            boolean finishInflate) throws  PullParserException, IOException {
        rInflate(parser, parent, parent.getContext(), attrs, finishInflate);
    }

 最后根据root与attachToRoot来判断是否添加到传递过来的父View,到此,基本上LayoutInflater加载布局的流程就出来,主要有以下几步:

  • 解析 文件
  • 创建根节点对象(如果是merge的话则直接遍历所有子节点)
  • 遍历所有子节点并创建子View

 LayoutInflater加载 文件的流程到此就梳理完了,但是还有一个很重要问题,就是View是如何创建的尼?上面只是说了View是通过createViewFromTag这个方法创建的,那这个方法的具体实现是什么尼?createViewFromTag最终调用的是如下方法

    View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
            boolean ignoreThemeAttr) {
        if (name.equals(\"view\")) {
            name = attrs.getAttributeValue(null, \"class\");
        }

        // Apply a theme wrapper, if allowed and one is specified.
        if (!ignoreThemeAttr) {
            final TypedArray ta = context.obtainStyledAttributes(attrs, ATTRS_THEME);
            final int themeResId = ta.getResourceId(0, 0);
            if (themeResId != 0) {
                context = new ContextThemeWrapper(context, themeResId);
            }
            ta.recycle();
        }

        if (name.equals(TAG_1995)) {
            // Let\'s party like it\'s 1995!
            return new  Layout(context, attrs);
        }

        try {
            View view;
            if (mFactory2 != null) {
                view = mFactory2.onCreateView(parent, name, context, attrs);
            } else if (mFactory != null) {
                view = mFactory.onCreateView(name, context, attrs);
            } else {
                view = null;
            }

            if (view == null && mPrivateFactory != null) {
                view = mPrivateFactory.onCreateView(parent, name, context, attrs);
            }

            if (view == null) {
                final   lastContext = mConstructorArgs[0];
                mConstructorArgs[0] = context;
                try {
                    if (-1 == name.indexOf(\'.\')) {
                        view = onCreateView(parent, name, attrs);
                    } else {
                        view = createView(name, null, attrs);
                    }
                } finally {
                    mConstructorArgs[0] = lastContext;
                }
            }

            return view;
        } catch (InflateException e) {
            throw e;

        } catch (ClassNotFoundException e) {
            final InflateException ie = new InflateException(attrs.getPositionDe ion()
                    + \": Error inflating class \" + name, e);
            ie.setStackTrace(EMPTY_STACK_TRACE);
            throw ie;

        } catch (Exception e) {
            final InflateException ie = new InflateException(attrs.getPositionDe ion()
                    + \": Error inflating class \" + name, e);
            ie.setStackTrace(EMPTY_STACK_TRACE);
            throw ie;
        }
    }

 通常情况下,自定义工厂mFactory2、mFactory和私有工厂mPrivateFactory是空的,当Activity继承自AppCompatActivity时,才会存在自定义Factory。所以就在onCreateView与createView中创建View,当是系统控件时,会调用onCreateView来补全控件名称,然后最终调用creatView方法。

    //补全控件名称
    protected View onCreateView(String name, AttributeSet attrs)
            throws ClassNotFoundException {
        return createView(name, \"android.view.\", attrs);
    }
   public final View createView(String name, String prefix, AttributeSet attrs)
            throws ClassNotFoundException, InflateException {
        Constructor<? extends View> constructor = sConstructorMap.get(name);
        if (constructor != null && !verifyClassLoader(constructor)) {
            constructor = null;
            sConstructorMap.remove(name);
        }
        Class<? extends View> clazz = null;

        try {
            Trace.traceBegin(Trace.TRACE_TAG_VIEW, name);

            if (constructor == null) {
                // Class not found in the cache, see if it\'s real, and try to add it
                clazz = mContext.getClassLoader().loadClass(
                        prefix != null ? (prefix + name) : name).asSubclass(View.class);

                if (mFilter != null && clazz != null) {
                    boolean allowed = mFilter. Class(clazz);
                    if (!allowed) {
                        failNotAllowed(name, prefix, attrs);
                    }
                }
                constructor = clazz.getConstructor(mConstructorSignature);
                constructor.setAccessible(true);
                sConstructorMap.put(name, constructor);
            } else {
                // If we have a filter, apply it to cached constructor
                if (mFilter != null) {
                    // Have we seen this name before?
                    Boolean allowedState = mFilterMap.get(name);
                    if (allowedState == null) {
                        // New class -- remember whether it is allowed
                        clazz = mContext.getClassLoader().loadClass(
                                prefix != null ? (prefix + name) : name).asSubclass(View.class);

                        boolean allowed = clazz != null && mFilter. Class(clazz);
                        mFilterMap.put(name, allowed);
                        if (!allowed) {
                            failNotAllowed(name, prefix, attrs);
                        }
                    } else if (allowedState.equals(Boolean.FALSE)) {
                        failNotAllowed(name, prefix, attrs);
                    }
                }
            }

              lastContext = mConstructorArgs[0];
            if (mConstructorArgs[0] == null) {
                // Fill in the context if not already within inflation.
                mConstructorArgs[0] = mContext;
            }
             [] args = mConstructorArgs;
            args[1] = attrs;
            //通过反射来创建View对象
            final View view = constructor.newInstance(args);
            if (view instanceof ViewStub) {
                // Use the same context when inflating ViewStub later.
                final ViewStub viewStub = (ViewStub) view;
                viewStub.setLayoutInflater(cloneInContext((Context) args[0]));
            }
            mConstructorArgs[0] = lastContext;
            return view;

        } catch (NoSuchMethodException e) {
            ..<					
收藏 打印