Android佈局解析者LayoutInflater

LayoutInflater可以把xml佈局文件裏內容加載成一個View,LayoutInflater可以說是Android裏的無名英雄,你經常用的到它,卻體會不到它的好。因爲隔壁的iOS兄弟是沒有 這種東西的,他們只能用代碼來寫佈局,需要應用跑起來才能看到效果。相比之下Android的開發者就幸福的多,但是大家有沒有相關xml是如何轉換成一個View的,今天我們就來分析 這個問題。

LayoutInflater也是通過Context獲取,它也是系統服務的一種,被註冊在ContextImpl的map裏,然後通過LAYOUT_INFLATER_SERVICE來獲取。

layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

LayoutInflater是一個抽象類,它的實現類是PhoneLayoutInflater。LayoutInflater會採用深度優先遍歷自頂向下遍歷View樹,根據View的全路徑名利用反射獲取構造器 從而構建View的實例。整個邏輯還是很清晰的,我們來具體看一看。

我們先來看看總的調度方法inflate(),這個也是我們最常用的

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

這個方法有三個參數:

int resource:佈局ID,也就是要解析的xml佈局文件,boolean attachToRoot表示是否要添加到父佈局root中去。這裏面還有個關鍵的參數root。它用來表示根佈局,這個就很常見的,我們在用 這個方法的時候,有時候給root賦值了,有時候直接給了null(給null的時候IDE會有警告提示),這個root到底有什麼作用呢?🤔

它主要有兩個方面的作用:

  • 當attachToRoot == true且root != null時,新解析出來的View會被add到root中去,然後將root作爲結果返回。
  • 當attachToRoot == false且root != null時,新解析的View會直接作爲結果返回,而且root會爲新解析的View生成LayoutParams並設置到該View中去。
  • 當attachToRoot == false且root == null時,新解析的View會直接作爲結果返回。

注意第二條和第三條是由區別的,你可以去寫個例子試一下,當root爲null時,新解析出來的View沒有LayoutParams參數,這時候你設置的layout_width和layout_height是不生效的。

說到這裏,有人可能有疑問了,Activity裏的佈局應該也是LayoutInflater加載的,我也沒做什麼處理,但是我設置的layout_width和layout_heigh參數都是可以生效的,這是爲什麼?🤔

這是因爲Activity內部做了處理,我們知道Activity的setContentView()方法,實際上調用的PhoneWindow的setContentView()方法。它調用的時候將Activity的頂級DecorView(FrameLayout) 作爲root傳了進去,mLayoutInflater.inflate(layoutResID, mContentParent)實際調用的是inflate(resource, root, root != null),所以在調用Activity的setContentView()方法時 可以將解析出的View添加到頂級DecorView中,我們設置的layout_width和layout_height參數也可以生效。

具體代碼如下:

@Override
public void setContentView(int layoutResID) {
    if (mContentParent == null) {
        installDecor();
    } else if (!hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
        mContentParent.removeAllViews();
    }

    if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
        final Scene newScene = Scene.getSceneForLayout(mContentParent, layoutResID,
                getContext());
        transitionTo(newScene);
    } else {

        mLayoutInflater.inflate(layoutResID, mContentParent);
    }
    mContentParent.requestApplyInsets();
    final Callback cb = getCallback();
    if (cb != null && !isDestroyed()) {
        cb.onContentChanged();
    }
    mContentParentExplicitlySet = true;
}

瞭解了inflate()方法各個參數的含義,我們正式來分析它的實現。


public abstract class LayoutInflater {

    public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
        final Resources res = getContext().getResources();
        if (DEBUG) {
            Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" ("
                    + Integer.toHexString(resource) + ")");
        }

        //獲取xml資源解析器XmlResourceParser
        final XmlResourceParser parser = res.getLayout(resource);
        try {
            return inflate(parser, root, attachToRoot);//解析View
        } finally {
            parser.close();
        }
    }
}

可以發現在該方法裏,主要完成了兩件事情:

  1. 獲取xml資源解析器XmlResourceParser。
  2. 解析View

我們先來看看XmlResourceParser是如何獲取的。

從上面的序列圖可以看出,調用了Resources的getLayout(resource)去獲取對應的XmlResourceParser。getLayout(resource)又去調用了Resources的loadXmlResourceParser() 方法來完成XmlResourceParser的加載,如下所示:

public class Resources {

     XmlResourceParser loadXmlResourceParser(@AnyRes int id, @NonNull String type)
             throws NotFoundException {
         final TypedValue value = obtainTempTypedValue();
         try {
             final ResourcesImpl impl = mResourcesImpl;
             //1. 獲取xml佈局資源,並保存在TypedValue中。
             impl.getValue(id, value, true);
             if (value.type == TypedValue.TYPE_STRING) {
                 //2. 加載對應的loadXmlResourceParser解析器。
                 return impl.loadXmlResourceParser(value.string.toString(), id,
                         value.assetCookie, type);
             }
             throw new NotFoundException("Resource ID #0x" + Integer.toHexString(id)
                     + " type #0x" + Integer.toHexString(value.type) + " is not valid");
         } finally {
             releaseTempTypedValue(value);
         }
     }   
}

可以發現這個方法又被分成了兩步:

  1. 獲取xml佈局資源,並保存在TypedValue中。
  2. 加載對應的loadXmlResourceParser解析器。

從上面的序列圖可以看出,資源的獲取涉及到resources.arsc的解析過程,這個我們已經在Resources的創建流程簡單聊過,這裏就不再贅述。通過 getValue()方法獲取到xml資源以後,就會調用ResourcesImpl的loadXmlResourceParser()方法對該佈局資源進行解析,以便得到一個UI佈局視圖。

我們來看看它的實現。

一 獲取XmlResourceParser

public class ResourcesImpl {

    XmlResourceParser loadXmlResourceParser(@NonNull String file, @AnyRes int id, int assetCookie,
               @NonNull String type)
               throws NotFoundException {
           if (id != 0) {
               try {
                   synchronized (mCachedXmlBlocks) {
                       //... 從緩存中查找xml資源

                       // Not in the cache, create a new block and put it at
                       // the next slot in the cache.
                       final XmlBlock block = mAssets.openXmlBlockAsset(assetCookie, file);
                       if (block != null) {
                           final int pos = (mLastCachedXmlBlockIndex + 1) % num;
                           mLastCachedXmlBlockIndex = pos;
                           final XmlBlock oldBlock = cachedXmlBlocks[pos];
                           if (oldBlock != null) {
                               oldBlock.close();
                           }
                           cachedXmlBlockCookies[pos] = assetCookie;
                           cachedXmlBlockFiles[pos] = file;
                           cachedXmlBlocks[pos] = block;
                           return block.newParser();
                       }
                   }
               } catch (Exception e) {
                   final NotFoundException rnf = new NotFoundException("File " + file
                           + " from xml type " + type + " resource ID #0x" + Integer.toHexString(id));
                   rnf.initCause(e);
                   throw rnf;
               }
           }

           throw new NotFoundException("File " + file + " from xml type " + type + " resource ID #0x"
                   + Integer.toHexString(id));
       }
}

我們先來看看這個方法的四個形參:

  • String file:xml文件的路徑
  • int id:xml文件的資源ID
  • int assetCookie:xml文件的資源緩存
  • String type:資源類型

ResourcesImpl會緩存最近解析的4個xml資源,如果不在緩存裏則調用AssetManger的openXmlBlockAsset()方法創建一個XmlBlock。XmlBlock是已編譯的xml文件的一個包裝類。

AssetManger的openXmlBlockAsset()方法的實現如下所示:

public final class AssetManager implements AutoCloseable {
   /*package*/ final XmlBlock openXmlBlockAsset(int cookie, String fileName)
       throws IOException {
       synchronized (this) {
           //...
           long xmlBlock = openXmlAssetNative(cookie, fileName);
           if (xmlBlock != 0) {
               XmlBlock res = new XmlBlock(this, xmlBlock);
               incRefsLocked(res.hashCode());
               return res;
           }
       }
       //...
   }
}

可以看出該方法會調用native方法openXmlAssetNative()去代開fileName指定的xml文件,成功打開該文件後,會得到C++層的ResXMLTree對象的地址xmlBlock,然後將xmlBlock封裝進 XmlBlock中返回給調用者。ResXMLTreed對象會存放打開後xml資源的內容。

上述序列圖裏的AssetManger.cpp的方法的具體實現也就是一個打開資源文件的過程,資源文件一般存放在APK中,APK是一個zip包,所以最終會調用openAssetFromZipLocked()方法打開xml文件。

XmlBlock封裝完成後,會調用XmlBlock對象的newParser()方法去構建一個XmlResourceParser對象,實現如下所示:

final class XmlBlock {
    public XmlResourceParser newParser() {
        synchronized (this) {
            //mNative指向的是C++層的ResXMLTree對象的地址
            if (mNative != 0) {
                return new Parser(nativeCreateParseState(mNative), this);
            }
            return null;
        }
    }

    private static final native long nativeCreateParseState(long obj);
}

mNative指向的是C++層的ResXMLTree對象的地址,native方法nativeCreateParseState()根據這個地址找到ResXMLTree對象,利用ResXMLTree對象對象構建一個ResXMLParser對象,並將ResXMLParser對象 的地址封裝進Java層的Parser對象中,構建一個Parser對象。所以他們的對應關係如下所示:

  • XmlBlock <--> ResXMLTree
  • Parser <--> ResXMLParser

就是建立了Java層與C++層的對應關係,實際的實現還是由C++層完成。

等獲取了XmlResourceParser對象以後就可以調用inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) 方法進行View的解析了,在解析View時 ,會先去調用rInflate()方法解析View樹,然後再調用createViewFromTag()方法創建具體的View,我們來詳細的看一看。

二 解析View樹

  1. 解析merge標籤,rInflate()方法會將merge下面的所有子View直接添加到根容器中,這裏我們也理解了爲什麼merge標籤可以達到簡化佈局的效果。
  2. 不是merge標籤那麼直接調用createViewFromTag()方法解析成佈局中的視圖,這裏的參數name就是要解析視圖的類型,例如:ImageView。
  3. 調用generateLayoutParams()f方法生成佈局參數,如果attachToRoot爲false,即不添加到根容器裏,爲View設置佈局參數。
  4. 調用rInflateChildren()方法解析當前View下面的所有子View。
  5. 如果根容器不爲空,且attachToRoot爲true,則將解析出來的View添加到根容器中,如果根佈局爲空或者attachToRoot爲false,那麼解析出來的額View就是返回結果。返回解析出來的結果。

接下來,我們分別看下View樹解析以及View的解析。

public abstract class LayoutInflater {

    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對象
               Context lastContext = (Context) mConstructorArgs[0];
               mConstructorArgs[0] = inflaterContext;

               //存儲根視圖
               View result = root;

               try {
                   // 獲取根元素
                   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("**************************");
                   }

                   //1. 解析merge標籤,rInflate()方法會將merge下面的所有子View直接添加到根容器中,這裏
                   //我們也理解了爲什麼merge標籤可以達到簡化佈局的效果。
                   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 {
                       //2. 不是merge標籤那麼直接調用createViewFromTag()方法解析成佈局中的視圖,這裏的參數name就是要解析視圖的類型,例如:ImageView
                       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);
                           }
                           //3. 調用generateLayoutParams()f方法生成佈局參數,如果attachToRoot爲false,即不添加到根容器裏,爲View設置佈局參數
                           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");
                       }

                       //4. 調用rInflateChildren()方法解析當前View下面的所有子View
                       rInflateChildren(parser, temp, attrs, true);

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

                       //如果根容器不爲空,且attachToRoot爲true,則將解析出來的View添加到根容器中
                       if (root != null && attachToRoot) {
                           root.addView(temp, params);
                       }

                       //如果根佈局爲空或者attachToRoot爲false,那麼解析出來的額View就是返回結果
                       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;
           }
     }
}

上面我們已經提到View樹的解析是有rInflate()方法來完成的,我們接着來看看View樹是如何被解析的。

public abstract class LayoutInflater {

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

        //1. 獲取樹的深度,執行深度優先遍歷
        final int depth = parser.getDepth();
        int type;

        //2. 逐個進行元素解析
        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)) {
                //3. 解析添加ad:focusable="true"的元素,並獲取View焦點。
                parseRequestFocus(parser, parent);
            } else if (TAG_TAG.equals(name)) {
                //4. 解析View的tag。
                parseViewTag(parser, parent, attrs);
            } else if (TAG_INCLUDE.equals(name)) {
                //5. 解析include標籤,注意include標籤不能作爲根元素。
                if (parser.getDepth() == 0) {
                    throw new InflateException("<include /> cannot be the root element");
                }
                parseInclude(parser, context, parent, attrs);
            } else if (TAG_MERGE.equals(name)) {
                //merge標籤必須爲根元素
                throw new InflateException("<merge /> must be the root element");
            } else {
                //6. 根據元素名進行解析,生成View。
                final View view = createViewFromTag(parent, name, context, attrs);
                final ViewGroup viewGroup = (ViewGroup) parent;
                final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
                //7. 遞歸調用解析該View裏的所有子View,也是深度優先遍歷,rInflateChildren內部調用的也是rInflate()方
                //法,只是傳入了新的parent View
                rInflateChildren(parser, view, attrs, true);
                //8. 將解析出來的View添加到它的父View中。
                viewGroup.addView(view, params);
            }
        }

        if (finishInflate) {
            //9. 回調根容器的onFinishInflate()方法,這個方法我們應該很熟悉。
            parent.onFinishInflate();
        }
    }

    //rInflateChildren內部調用的也是rInflate()方法,只是傳入了新的parent View
    final void rInflateChildren(XmlPullParser parser, View parent, AttributeSet attrs,
            boolean finishInflate) throws XmlPullParserException, IOException {
        rInflate(parser, parent, parent.getContext(), attrs, finishInflate);
    }

}

上述方法描述了整個View樹的解析流程,我們來概括一下:

  1. 獲取樹的深度,執行深度優先遍歷.
  2. 逐個進行元素解析。
  3. 解析添加ad:focusable="true"的元素,並獲取View焦點。
  4. 解析View的tag。
  5. 解析include標籤,注意include標籤不能作爲根元素,而merge必須作爲根元素。
  6. 根據元素名進行解析,生成View。
  7. 遞歸調用解析該View裏的所有子View,也是深度優先遍歷,rInflateChildren內部調用的也是rInflate()方法,只是傳入了新的parent View。
  8. 將解析出來的View添加到它的父View中。
  9. 回調根容器的onFinishInflate()方法,這個方法我們應該很熟悉。

你可以看到,負責解析單個View的正是createViewFromTag()方法,我們再來分析下這個方法。

三 解析View

public abstract class LayoutInflater {

        View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
                boolean ignoreThemeAttr) {

            //1. 解析view標籤。注意是小寫view,這個不太常用,下面會說。
            if (name.equals("view")) {
                name = attrs.getAttributeValue(null, "class");
            }

            //2. 如果標籤與主題相關,則需要將context與themeResId包裹成ContextThemeWrapper。
            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();
            }

            //3. BlinkLayout是一種會閃爍的佈局,被包裹的內容會一直閃爍,像QQ消息那樣。
            if (name.equals(TAG_1995)) {
                // Let's party like it's 1995!
                return new BlinkLayout(context, attrs);
            }

            try {
                View view;

                //4. 用戶可以設置LayoutInflater的Factory來進行View的解析,但是默認情況下
                //這些Factory都是爲空的。
                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);
                }

                //5. 默認情況下沒有Factory,而是通過onCreateView()方法對內置View進行解析,createView()
                //方法進行自定義View的解析。
                if (view == null) {
                    final Object lastContext = mConstructorArgs[0];
                    mConstructorArgs[0] = context;
                    try {
                        //這裏有個小技巧,因爲我們在使用自定義View的時候是需要在xml指定全路徑的,例如:
                        //com.guoxiaoxing.CustomView,那麼這裏就有個.了,可以利用這一點判定是內置View
                        //還是自定義View,Google的工程師很機智的。😎
                        if (-1 == name.indexOf('.')) {
                            //內置View解析
                            view = onCreateView(parent, name, attrs);
                        } else {
                            //自定義View解析
                            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;
            }
        }
}

單個View的解析流程也很簡單,我們來梳理一下:

  1. 解析View標籤。
  2. 如果標籤與主題相關,則需要將context與themeResId包裹成ContextThemeWrapper。
  3. BlinkLayout是一種會閃爍的佈局,被包裹的內容會一直閃爍,像QQ消息那樣。
  4. 用戶可以設置LayoutInflater的Factory來進行View的解析,但是默認情況下這些Factory都是爲空的。
  5. 默認情況下沒有Factory,而是通過onCreateView()方法對內置View進行解析,createView()方法進行自定義View的解析。這裏有個小技巧,因爲 我們在使用自定義View的時候是需要在xml指定全路徑的,例如:com.guoxiaoxing.CustomView,那麼這裏就有個.了,可以利用這一點判定是內置View 還是自定義View,Google的工程師很機智的。😎

關於view標籤

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

在使用時,相當於所有控件標籤的父類一樣,可以設置class屬性,這個屬性會決定view這個節點會是什麼控件。

關於BlinkLayout

這個也是個冷門的控件,本質上是一個FrameLayout,被它包裹的控件會像電腦版的QQ小企鵝那樣一直閃爍。

<blink
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="這個控件會一直閃爍"/>

</blink>

關於onCreateView()與createView()

這兩個方法在本質上都是一樣的,只是onCreateView()會給內置的View前面加一個前綴,例如:android.widget,方便開發者在寫內置View的時候,不用謝全路徑名。 前面我們也提到了LayoutInflater是一個抽象類,我們實際使用的PhoneLayoutInflater,這個類的實現很簡單,它重寫了LayoutInflater的onCreatView()方法,該 方法就是做了一個給內置View加前綴的事情。

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

    @Override protected View onCreateView(String name, AttributeSet attrs) throws ClassNotFoundException {

        //循環遍歷三種前綴,嘗試創建View
        for (String prefix : sClassPrefixList) {
            try {
                View view = createView(name, prefix, attrs);
                if (view != null) {
                    return view;
                }
            } catch (ClassNotFoundException e) {
                // In this case we want to let the base class take a crack
                // at it.
            }
        }
        return super.onCreateView(name, attrs);
    }
    public LayoutInflater cloneInContext(Context newContext) {
        return new PhoneLayoutInflater(this, newContext);
    }
}

這樣一來,真正的View構建還是在createView()方法裏完成的,createView()主要根據完整的類的路徑名利用反射機制構建View對象,我們具體來 看看createView()方法的實現。

public abstract class LayoutInflater {

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

            //1. 從緩存中讀取構造函數。
            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

                    //2. 沒有在緩存中查找到構造函數,則構造完整的路徑名,並加裝該類。
                    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);
                        }
                    }
                    //3. 從Class對象中獲取構造函數,並在sConstructorMap做下緩存,方便下次使用。
                    constructor = clazz.getConstructor(mConstructorSignature);
                    constructor.setAccessible(true);
                    sConstructorMap.put(name, constructor);
                } else {
                    //4. 如果sConstructorMap中有當前View構造函數的緩存,則直接使用。
                    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;

                //5. 利用構造函數,構建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]));
                }
                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);
            }
        }   
}

好了,到這篇文章爲止,我們對整個Android顯示框架的原理分析就算是告一段落了,在這些文章裏我們側重的是Client端的分析,WindowManagerService、SurfaceFlinger這些Server端的 並沒有過多的涉及,因爲對大部分開發者而言,紮實的掌握Client端的原理就足夠了。等到你完全掌握了Client端的原理或者是需要進行Android Framework層的開發,可以進一步去深入Server 端的原理。

關於Android顯示框架主要包括五篇文章:

後續我們會接着進行

  • Android組件框架
  • Android動畫框架
  • Android通信框架
  • Android多媒體框架

等Android子系統的分析,後續的內容可以關注Android open source project analysis項目。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章