天天看點

View繪制詳解,從LayoutInflater談起

自定義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方法的一個簡單解讀,整體來說貌似沒有什麼難點,有問題歡迎留言讨論。

以上。

轉載于:https://www.cnblogs.com/lenve/p/5989998.html