【Android原始碼】View的建立流程

指間沙似流年發表於2017-12-23

通過上篇的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的建立流程。

相關文章