View绘制详解,从LayoutInflater谈起

来源:互联网 发布:qq永久封号软件 编辑:程序博客网 时间:2024/06/10 20:42

自定义View算是Android开发中的重中之重了,很多小伙伴可能或多或少都玩过自定义View,对View的绘制流程也有一定的理解。那么现在我想通过几篇博客来详细介绍View的绘制流程,以便使我们更加深刻的理解自定义View。

如果小伙伴们还没用过自定义View或者用的不多的话,那么建议通过以下几篇文章先来热个身:

1.Android自定义View之ProgressBar出场记

2.android自定义View之NotePad出鞘记

3.android自定义View之仿通讯录侧边栏滑动,实现A-Z字母检索

4.android自定义View之钟表诞生记

5.自己动手,丰衣足食!一大波各式各样的ImageView来袭!

6.Android开发之Path类使用详解,自绘各种各样的图形!

7.自定义View

OK,View的世界浩如烟海,不过凡事只要抓住纲就好解决,所谓提纲挈领嘛。那我这里就打算从LayoutInflater这个布局管理器开始我们的View绘制详解之旅。so,开始吧!

使用LayoutInflater加载一个布局文件,一般情况下,我们通过下面的方式来获取一个LayoutInflater实例:

LayoutInflater inflater = LayoutInflater.from(this);


点到这个方法里边,我们发现这里实际上是调用了系统服务,如下:

    public static LayoutInflater from(Context context) {        LayoutInflater LayoutInflater =                (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);        if (LayoutInflater == null) {            throw new AssertionError("LayoutInflater not found.");        }        return LayoutInflater;    }

看到这里小伙伴们应该明白了,获取LayoutInflater我们还有另外一种方式:

LayoutInflater layoutInflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);

两种方式都可以获取一个LayoutInflater实例,拿到实例后,接下来就可以加载布局了,加载布局时我们使用inflate方法,该方法有两个重载的方法,一个是两个参数,一个是三个参数,关于这两个方法的差异小伙伴们如果还不懂可以移步这里三个案例带你看懂LayoutInflater中inflate方法两个参数和三个参数的区别,不论是两个参数还是三个参数,inflate方法最后都会到达这里:

    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;            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();                                if (DEBUG) {                    System.out.println("**************************");                    System.out.println("Creating root view: "                            + name);                    System.out.println("**************************");                }                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 {                    // 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;        }    }

小伙伴们请看,上面这个方法虽然很长,但是逻辑却很简单,前面几行代码都很简单,就是XML的解析,我们看到Google中布局XML的解析使用了PULL解析的方式,在第24行,首先获取了XML文件根节点的名称,第33行,如果根节点是merge的话,那么要求根节点必须添加到某一个容器中,否则会抛异常(如果小伙伴们对merge这个节点尚不了解,请移步这里android开发之merge结合include优化布局)。如果根节点不是merge,则在第42行通过createViewFromTag方法创建一个View(该方法稍后详述),这个View实际上就是我们要加载布局的根节点,加载到根View之后,加载到根View之后,如果root不为null,则在第52行根据root生成一个LayoutParams,第53行,如果我们设置了不将加载进来的布局加载到root中,即我们传入的attachToRoot为false的话,则将刚刚加载进来的params设置给temp(temp是我们要加载布局的根节点),然后在65行通过rInflateChildren方法开始去读取这个根节点下的所有子控件(该方法稍后详述),第73行,如果我们设置了root不为null,并且要将添加进来的布局加入到root中,则会执行root.addView方法。第79行,如果root为null,则attachToRoot不管是什么都会执行第80行,将temp赋值给result。小伙伴们请注意这个result本身的值就是root。最后将result返回。OK如此看来整个inflate方法思路还是非常清晰的,并没有什么难以理解的地方。接下来我们再来看一看系统是怎么样创建根布局的,以及是怎样创建根布局中的子元素的。首先我们来看看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 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 {                    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.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;        }    }

小伙伴们注意,在这个方法的第40行,首先判断了要实例化的节点的名字中是否包含一个点,包含的话说明该View不是由android.jar提供的,这种情况对应一种解析方式,不包含说明该View是由系统提供的,对应一种解析方式,如果name中不包含点,则最终会调用下面的方法:

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

小伙伴们请看,这里系统会自动为View添加上包名,我们再来看看这个createView方法(小伙伴们注意,如果我们的View是自定义View的话,最终也会来到这个方法中):

    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.onLoadClass(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.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;            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]));            }            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);        }    }

这个方法虽然有点长,但是核心目的却很清晰,就是根据View的名称,通过Java中的反射机制来获取一个View实例并返回。OK,以上就是对创建根布局方法createViewFromTag的讲解,其实严格来说,这个方法是创建一个View,我们一会在创建容器中的子View的时候,还会再用到这个方法。OK,现在我们再回到inflate方法的第65行,这里又一个方法叫做rInflateChildren,我们来看看该方法:

void rInflate(XmlPullParser parser, View parent, Context context,            AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {        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();                        if (TAG_REQUEST_FOCUS.equals(name)) {                parseRequestFocus(parser, parent);            } else if (TAG_TAG.equals(name)) {                parseViewTag(parser, parent, attrs);            } else if (TAG_INCLUDE.equals(name)) {                if (parser.getDepth() == 0) {                    throw new InflateException("<include /> cannot be the root element");                }                parseInclude(parser, context, parent, attrs);            } else if (TAG_MERGE.equals(name)) {                throw new InflateException("<merge /> must be the root element");            } else {                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);                viewGroup.addView(view, params);            }        }        if (finishInflate) {            parent.onFinishInflate();        }    }

这个方法倒是很简单,并不长,核心代码就是28行到32行,这里还是调用了上文所说的createViewFromTag方法来获取一个View的实例,然后第31行通过一个递归方法来遍历容器中的所有控件,并将获取到的控件添加到对应的viewGroup中。


OK,以上就是对inflate方法的一个简单解读,整体来说貌似没有什么难点,有问题欢迎留言讨论。


以上。


2 0
原创粉丝点击