LayoutInflater源码分析(二)

上一篇LayoutInflater源码分析(一)我们分析了LayoutInflater的from()方法,这节我们来分析一下inflate()方法。

view = LayoutInflater.from(parent.getContext())
                    .inflate(R.layout.item_vip, parent, false);

最终都会进入到如下代码:

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

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

            //令人窒息操作part one~
            try {
                // Look for the root node.
                int type;
                while ((type = parser.next()) != XmlPullParser.START_TAG &&
                        type != XmlPullParser.END_DOCUMENT) {
                    // Empty
                }

                if (type != XmlPullParser.START_TAG) {
                    throw new InflateException(parser.getPositionDescription()
                            + ": No start tag found!");
                }

                final String name = parser.getName();
                
                //去掉部分代码
                //令人窒息操作part two ~
                if (TAG_MERGE.equals(name)) {
                    if (root == null || !attachToRoot) {
                        throw new InflateException("<merge /> can be used only with a valid "
                                + "ViewGroup root and attachToRoot=true");
                    }

                    rInflate(parser, root, inflaterContext, attrs, false);
                } else {
                     //令人窒息操作part three ~
                    // 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);
                        }
                    }

                    if (DEBUG) {
                        System.out.println("-----> start inflating children");
                    }

                    // Inflate all children under temp against its context.
                    rInflateChildren(parser, temp, attrs, true);

                    if (DEBUG) {
                        System.out.println("-----> done inflating children");
                    }

                    // 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;
                    }
                }

            } catch (XmlPullParserException e) {
                final InflateException ie = new InflateException(e.getMessage(), e);
                ie.setStackTrace(EMPTY_STACK_TRACE);
                throw ie;
            } catch (Exception e) {
                final InflateException ie = new InflateException(parser.getPositionDescription()
                        + ": " + e.getMessage(), e);
                ie.setStackTrace(EMPTY_STACK_TRACE);
                throw ie;
            } finally {
                // Don't retain static reference on context.
                mConstructorArgs[0] = lastContext;
                mConstructorArgs[1] = null;

                Trace.traceEnd(Trace.TRACE_TAG_VIEW);
            }

            return result;
        }
    }

通过代码和注释我们可以看到,拿到XmlResourceParser parser是用于节点的解析。

比如part one 从头到尾遍历xml文件的标签,直到
文档结束才跳出循环。如果该xml没有开始标签,则抛异常。

part two 讲的是什么呢?TAG_MERGE=”merge”,如果读到的标签是merge,判断是否有父View,没有则抛异常,有则跳转到rInflate()解析merge的xml。

part three就是当前的标签没有其他子xml,要直接解析啦。关键方法就是createViewFromTag()方法了。

(一)rInflate()解析

void rInflate(XmlPullParser parser, View parent, Context context,
            AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {
        //获取该xml的深度 ~~
        final int depth = parser.getDepth();
        int type;
        
        while (((type = parser.next()) != XmlPullParser.END_TAG ||
                parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
            
            if (type != XmlPullParser.START_TAG) {
                continue;
            }

            final String name = parser.getName();
            //判断标签是否为requestFocus[1]。requestFocus标签于指定屏幕内的焦点View
            if (TAG_REQUEST_FOCUS.equals(name)) {
                parseRequestFocus(parser, parent);
            //判断标签是否为tag。
            //设置一个文本标签。可以通过View.getTag()或 for with View.findViewWithTag()检索含有该标签字符串的View。
            //但一般最好通过ID来查询View,因为它的速度更快,并且允许编译时类型检查。
            } 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。如果是,则直接抛出异常,因为Merge必须为根元素,也就是深度为0的节点。
            } else if (TAG_MERGE.equals(name)) {
                throw new InflateException("<merge /> must be the root element");
            } else {
                //没啥奇奇怪怪标签了。又出现了这个createViewFromTag()方法。这个方法其实就是根据标签(节点名)称创建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添加进Parent布局
                viewGroup.addView(view, params);
            }
        }
        //通知父View,解析完成。
        if (finishInflate) {
            parent.onFinishInflate();
        }
    }

我们点击进入rInflateChildren()方法,发现其实也是调用的rInflate()方法:

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

(二)createViewFromTag()解析

View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
            boolean ignoreThemeAttr) {
        //解析view标签,注意哦,是view不是View,这个标签一般大家不太常用。[2]
        if (name.equals("view")) {
            name = attrs.getAttributeValue(null, "class");
        }

         //如果需要该标签与主题相关,需要对context进行包装,将主题信息加入context包装类ContextWrapper
        //好吧其实我不知道这个是什么鬼,哈哈哈
        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();
        }
        //TAG_1995="blink"
        if (name.equals(TAG_1995)) {
            //BlinkLayou继承自FrameLayout,它包裹的内容会一直闪烁。[3]
            return new BlinkLayout(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 Object lastContext = mConstructorArgs[0];
                mConstructorArgs[0] = context;
                try {
                    //indexOf()的用法:
                    //返回字符中indexof(string)中字串string在父串中首次出现的位置,从0开始!没有返回-1。
                    //下面判断语句是对自定义View和原生的控件进行判断。如果name中包含.即为自定义View,否则为原生的View控件
                    //例如:<Button>
                    if (-1 == name.indexOf('.')) {
                        view = onCreateView(parent, name, attrs);
                    } else {
                        //自定义控件,例如: <com.xxx.xxx.MyView>
                        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.getPositionDescription()
                    + ": Error inflating class " + name, e);
            ie.setStackTrace(EMPTY_STACK_TRACE);
            throw ie;

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

[2]view相当于所有控件标签的父类一样,可以设置class属性,这个属性会决定view这个节点会变成什么控件。

 <view
        class="RelativeLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent"></view>

[3]blink这个标签很有好玩,大家可以自己试试下面的代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <blink
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        >
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="一闪一闪亮晶晶"
            android:textSize="18sp"
            android:textColor="@android:color/holo_orange_light"
            />

    </blink>
</LinearLayout>

我们看到mFactory 和mFactory2 ,他们的类型是Factory和Factory2。而实际上Factory和Factory2都是一个接口,需要自己实现,并且Factory2继承自Factory,从而扩展出一个参数,就是增加了该节点的父View。

public interface Factory2 extends Factory {
        public View onCreateView(View parent, String name, Context context, AttributeSet attrs);
    }

那么这两个Factory是用来干嘛的呢?Factory和Factory2其实LayoutInflater解析View时的一种扩展实现,可以额外的对View处理,设置Factory和Factory2需要通过setFactory()或者setFactory2()来实现。

有没有个具体例子演示一下?鸿洋大神给过一个例子,我稍作修改了代码。xml中有一个TextView,但是经过下面代码修改,将TextView变成了Button:

public class MainActivity extends AppCompatActivity
{
    private static final String TAG = "MainActivity";

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        LayoutInflaterCompat.setFactory(LayoutInflater.from(this), new LayoutInflaterFactory()
        {
            @Override
            public View onCreateView(View parent, String name, Context context, AttributeSet attrs)
            {
                //这这这,小哥哥我在这~
                if (name.equals("TextView"))
                   {
                      Button button = new Button(context, attrs);
                      return button;
                   }
                }

                return null;
            }
        });
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }

具体查看:Android 探究 LayoutInflater setFactory

需要强调一点,LayoutInflater内部定义了一个boolean类型的mFactorySet开关,其值默认值为false,当我们调用过setFactory()或者是setFactory2()后mFactorySet为true,若我们再次调用这俩方法时会抛出异常,也就是说每一个LayoutInflater实例对象只能赋值一次Factory,若再想赋成其他值只能通过反射先把mFactorySet的值置为false防止抛异常。具体的大家可以去看setFactory()和setFactory2()代码,我这边不叙述了。

我们前面代码标注过,如果是原生控件,那它走:

view = onCreateView(parent, name, attrs);

我们点击方法看一下:

protected View onCreateView(View parent, String name, AttributeSet attrs)
            throws ClassNotFoundException {
        return onCreateView(name, attrs);
    }

再点进去onCreateView()看下:

protected View onCreateView(String name, AttributeSet attrs)
            throws ClassNotFoundException {
        return createView(name, "android.view.", attrs);
    }

我们可以看到标签名自动帮我们加上了”android.view”,再点进createView()方法,发现最终该原生控件走的是和自定义控件一样的createView()方法。这个方法有点长,大家坚持一会儿,本章快结束了。

public final View createView(String name, String prefix, AttributeSet attrs)
            throws ClassNotFoundException, InflateException {

         // 以View的name为key, 查询构造函数的缓存map中是否已经存在该View的构造函数.
        Constructor<? extends View> constructor = sConstructorMap.get(name);
         //verifyClassLoader()判断ClassLoader是否安全
        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) {
               // 如果传入的第二个参数prefix为null,就说明name是完整的包名,是自定义控件,直接反射加载自定义View。
               //如果第二个参数不为 null,就由前缀+name组成完整的类名。
                clazz = mContext.getClassLoader().loadClass(
                        prefix != null ? (prefix + name) : name).asSubclass(View.class);
                 // 如果有自定义的过滤器并且加载到字节码,则通过过滤器判断是否允许加载该View
                if (mFilter != null && clazz != null) {
                    boolean allowed = mFilter.onLoadClass(clazz);
                    if (!allowed) {
                        failNotAllowed(name, prefix, attrs);
                    }
                }
                // 得到构造函数
                constructor = clazz.getConstructor(mConstructorSignature);
                constructor.setAccessible(true);
                 // 缓存构造函数
                sConstructorMap.put(name, constructor);
            } else {
                if (mFilter != null) {
                    // 过滤的map是否包含了此类名
                    Boolean allowedState = mFilterMap.get(name);
                   
                    if (allowedState == null) {
                         //加载Class对象操作
                        // New class -- remember whether it is allowed
                        clazz = mContext.getClassLoader().loadClass(
                                prefix != null ? (prefix + name) : name).asSubclass(View.class);
                        //判断Class是否可被加载
                        boolean allowed = clazz != null && mFilter.onLoadClass(clazz);
                        mFilterMap.put(name, allowed);
                        if (!allowed) {
                            failNotAllowed(name, prefix, attrs);
                        }
                    } else if (allowedState.equals(Boolean.FALSE)) {
                        failNotAllowed(name, prefix, attrs);
                    }
                }
            }

            Object[] args = mConstructorArgs;
            args[1] = attrs;
            //如果过滤器不存在,直接实例化该View
            final View view = constructor.newInstance(args);
            //如果View属于ViewStub那么需要给ViewStub设置一个克隆过的LayoutInflater
            if (view instanceof ViewStub) {
                // Use the same context when inflating ViewStub later.
                final ViewStub viewStub = (ViewStub) view;
                viewStub.setLayoutInflater(cloneInContext((Context) args[0]));
            }
            return view;

        } catch (NoSuchMethodException e) {
            final InflateException ie = new InflateException(attrs.getPositionDescription()
                    + ": Error inflating class " + (prefix != null ? (prefix + name) : name), e);
            ie.setStackTrace(EMPTY_STACK_TRACE);
            throw ie;

        } catch (ClassCastException e) {
            // If loaded class is not a View subclass
            final InflateException ie = new InflateException(attrs.getPositionDescription()
                    + ": Class is not a View " + (prefix != null ? (prefix + name) : name), e);
            ie.setStackTrace(EMPTY_STACK_TRACE);
            throw ie;
        } catch (ClassNotFoundException e) {
            // If loadClass fails, we should propagate the exception.
            throw e;
        } catch (Exception e) {
            final InflateException ie = new InflateException(
                    attrs.getPositionDescription() + ": Error inflating class "
                            + (clazz == null ? "<unknown>" : clazz.getName()), e);
            ie.setStackTrace(EMPTY_STACK_TRACE);
            throw ie;
        } finally {
            Trace.traceEnd(Trace.TRACE_TAG_VIEW);
        }
    }

具体的注释我写在代码里了,大家自行查阅。希望看完文章,大家花个两分钟思考一下LayoutInflate的一些主要方法的作用是什么、xml是怎么转变成view的。有机会我会再开一篇文章,讲讲LayoutInflater的一点实战内容。

感谢:Android 中LayoutInflater(布局加载器)系列博文说明等网络各种博客。欢迎纠错,互相学习~

[1]

<EditText   
        android:id="@+id/et_result"  
        android:layout_width="fill_parent"  
        android:layout_height="wrap_content"  
        android:inputType="number">  
        <requestFocus />  
    </EditText>  
    原文作者:小阿拉
    原文地址: https://www.jianshu.com/p/683d8e40664e
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞