【Android源碼】View的創建流程

通過上篇的LayoutInflater 分析,我們知道了LayoutInflater服務的注冊流程,最終是通過PhoneLayoutInflater對象的onCreateView來創建對應的View對象的。那么具體的View的創建過程是怎么樣的呢,今天我們來一起分析一下。

通常情況下,一個Activity的界面的創建是通過setContentView來引入布局。

mWindow = new PhoneWindow(this, window);

public void setContentView(@LayoutRes int layoutResID) {
   getWindow().setContentView(layoutResID);
   initWindowDecorActionBar();
}

而Activity的setContentView方法是通過調用Window的setContentView方法,而Window是一個抽象對象,它的具體實現類就是PhoneWindow。在PhoneWindow中找到setContentView方法:

@Override
public void setContentView(int layoutResID) {
     // 如果mContentParent為空時先構建
   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 {
            // 通過LayoutInflater解析布局
       mLayoutInflater.inflate(layoutResID, mContentParent);
   }
   mContentParent.requestApplyInsets();
   final Callback cb = getCallback();
   if (cb != null && !isDestroyed()) {
       cb.onContentChanged();
   }
}

可以發現,setContentView也是通過LayoutInflater加載布局加載到mContentParent中。我們再看inflate方法:

public View inflate(@LayoutRes int resource, @Nullable ViewGroup root) {
   return inflate(resource, root, root != null);
}

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) + ")");
   }

   final XmlResourceParser parser = res.getLayout(resource);
   try {
       return inflate(parser, root, attachToRoot);
   } finally {
       parser.close();
   }
}

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 {
           // Look for the root node.
           int type;
           // 找到root元素
           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();
           
                // 解析merge標簽
           if (TAG_MERGE.equals(name)) {
                    // 如果是merge標簽調用新方法,將merge標簽內的元素全部加載到父視圖中
               rInflate(parser, root, inflaterContext, attrs, false);
           } else {
                // 通過xml的tag來解析根視圖
                final View temp = createViewFromTag(root, name, inflaterContext, attrs);
                // 不是merge標簽,直接解析布局中的視圖
               ViewGroup.LayoutParams params = null;

               if (root != null) {
                   // 生成布局參數
                   params = root.generateLayoutParams(attrs);
                   if (!attachToRoot) {
                       temp.setLayoutParams(params);
                   }
               }
               // Inflate all children under temp against its context.
               // 解析temp視圖下的所有view
               rInflateChildren(parser, temp, attrs, true);

               // 如果root不為空并且attachToRoot為true,將temp加入到父視圖中
               if (root != null && attachToRoot) {
                   root.addView(temp, params);
               }
               // 如果root為空 或者 attachToRoot為false,返回的結果就是temp
               if (root == null || !attachToRoot) {
                   result = temp;
               }
           }

       } catch (XmlPullParserException e) {
           throw ie;
       } catch (Exception e) {
           throw ie;
       } finally {
           // Don't retain static reference on context.
           mConstructorArgs[0] = lastContext;
           mConstructorArgs[1] = null;

           Trace.traceEnd(Trace.TRACE_TAG_VIEW);
       }

       return result;
   }
}

最終調用public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot)方法,其中第一個參數是xml解析器,第二個參數是要解析布局的父視圖,第三個參數標識是否需要加入到父視圖中。

上面的inflate方法所做的操作主要有以下幾步:

  1. 解析xml的根標簽
  2. 如果根標簽是merge,那么調用rInflate解析,將merge標簽下的所有子View直接添加到根標簽中
  3. 如果不是merge,調用createViewFromTag解析該元素
  4. 調用rInflate解析temp中的子View,并將這些子View添加到temp中
  5. 通過attachToRoot,返回對應解析的根視圖

我們先看createViewFromTag方法:

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

   try {
       View view;

       if (view == null) {
           final Object lastContext = mConstructorArgs[0];
           mConstructorArgs[0] = context;
           try {
                // 通過.來判斷是自定義View還是內置View
               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) {
       throw ie;
   }
}

我們可以發現,解析View的時候是通過.來判斷是內置的View還是自定義的View的,那么我們就能知道為什么在寫布局文件中自定義的View需要完整路徑了。

在解析內置View的時候就是通過類似于PhoneLayoutInflater的onCreateView的解析方式,通過在name前加上android.view.最終也是調用createView來解析。

而自定義view則是在調用createView(name, null, attrs)時,第二個參數的前綴傳遞null。

public final View createView(String name, String prefix, AttributeSet attrs)
       throws ClassNotFoundException, InflateException {
   // 從緩存中獲取view的構造函數
   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) {
           // 如果前綴不為空構造完整的View路徑并加載該類
           clazz = mContext.getClassLoader().loadClass(
                   prefix != null ? (prefix + name) : name).asSubclass(View.class);
           // 獲取該類的構造函數
           constructor = clazz.getConstructor(mConstructorSignature);
           constructor.setAccessible(true);
           // 將構造函數加入緩存中
           sConstructorMap.put(name, constructor);
       } else {
       }

       Object[] 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]));
       }
       return view;

   }
}

createView相對簡單,通過判斷前綴,來構建View的完整路徑,并將該類加載到虛擬機中,獲取構造函數并緩存,再通過構造函數創建該View對象,并返回。這個時候我們就獲得了根視圖。接著調用rInflateChildren方法解析子View,并最終調用rInflate方法:

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)) {// 解析tag標簽
           parseViewTag(parser, parent, attrs);
       } else if (TAG_INCLUDE.equals(name)) {// 解析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 {
            // 解析到普通的子View,并調用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加入到父視圖中
           viewGroup.addView(view, params);
       }
   }

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

rInflate方法通過深度優先遍歷的方式來構造視圖樹,當解析到一個View的時候就再次調用rInflate方法,直到將路徑下的最后一個元素,并最終將View加入到父視圖中。

這就是完整的View的創建流程。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容