Android View繪製及事件(二)setContentView()源碼,LayoutInflater加載View的過程

 

前言

 @Override
 protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
 }

通常情況下,我們創建一個Activity時,會通過setContentView來引入佈局,將界面視圖展現給用戶看見。那麼,爲什麼通過setContentView()就能將佈局文件加載到界面中呢?

一、setContentView()源碼分析

由於版本不同,有繼承Activity的頁面和繼承AppCompatActivity,但原理都一樣,基本都離不開LayoutInflater.from(mContext).inflate(resId, contentParent); 的方式,將佈局解析到DecorView根佈局中。

繼承Activity

SetContentView源碼如下:

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

getWindow()返回的是一個Window實例,調用Window的setContentView方法。我們知道,Window是一個抽象對象,它的具體實現類就是PhoneWindow。那麼,這裏PhoneWindow中的setContentView方法實現如下:

@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();
   }
}

繼承AppCompatActivity

    @Override
    public void setContentView(@LayoutRes int layoutResID) {
        getDelegate().setContentView(layoutResID);
    }

    @Override
    public void setContentView(View view) {
        getDelegate().setContentView(view);
    }

    @Override
    public void setContentView(View view, ViewGroup.LayoutParams params) {
        getDelegate().setContentView(view, params);
    }

實際上是通過調用getDelegate().setContentView()。getDelegate()源碼實現如下:

 public AppCompatDelegate getDelegate() {
        if (mDelegate == null) {
            mDelegate = AppCompatDelegate.create(this, this);
        }
        return mDelegate;
}

AppCompatDelegate.create()源碼:

 private static AppCompatDelegate create(Context context, Window window,
            AppCompatCallback callback) {
        final int sdk = Build.VERSION.SDK_INT;
        if (BuildCompat.isAtLeastN()) {
            return new AppCompatDelegateImplN(context, window, callback);
        } else if (sdk >= 23) {
            return new AppCompatDelegateImplV23(context, window, callback);
        } else if (sdk >= 14) {
            return new AppCompatDelegateImplV14(context, window, callback);
        } else if (sdk >= 11) {
            return new AppCompatDelegateImplV11(context, window, callback);
        } else {
            return new AppCompatDelegateImplV9(context, window, callback);
        }
    }

AppCompatDelegate是個什麼鬼?  其實這裏利用設計模式中的代理模式,AppCompatDelegate是Activity的委託類,這樣就無法直接繼承和訪問Activity中的方法,提高了Activity的安全性和擴展性。

AppCompatDelegate是個抽象類,裏面定義了抽象方法和普通方法。例如,setContentView()、findViewByid(int)、onCreate()~onDestory()生命週期、onConfigurationChanged()屏幕翻轉、onSaveInstanceState(Bundle)保存實例等。

這裏,我們還得重點看 setContentView() 實現代碼。


    @Override
    public void setContentView(View v) {
        ensureSubDecor();
        ViewGroup contentParent = (ViewGroup) mSubDecor.findViewById(android.R.id.content);
        contentParent.removeAllViews();
        contentParent.addView(v);
        mOriginalWindowCallback.onContentChanged();
    }

    @Override
    public void setContentView(int resId) {
        ensureSubDecor();
        ViewGroup contentParent = (ViewGroup) mSubDecor.findViewById(android.R.id.content);
        contentParent.removeAllViews();
        LayoutInflater.from(mContext).inflate(resId, contentParent);
        mOriginalWindowCallback.onContentChanged();
    }

    @Override
    public void setContentView(View v, ViewGroup.LayoutParams lp) {
        ensureSubDecor();
        ViewGroup contentParent = (ViewGroup) mSubDecor.findViewById(android.R.id.content);
        contentParent.removeAllViews();
        contentParent.addView(v, lp);
        mOriginalWindowCallback.onContentChanged();
    }

說到底,主要還是用到了LayoutInflater.inflate() 佈局加載解析方法將Activity中的佈局添加到父佈局中。

這個 LayoutInflater.inflate() 我們並不陌生的,比如RecycleView做列表適配器的時候都會用它加載item的view啊。

二、LayoutInflater.inflate() 

inflater.inflate(layoutId, null);

inflater.inflate(layoutId, root,false);

inflater.inflate(layoutId, root,true);

/**
 * parser xml解析器
 * root  父容器
 * attackToRoot 是否加入到父容器中
 */
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
   synchronized (mConstructorArgs) {

       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;
           // 找到root元素
           while ((type = parser.next()) != XmlPullParser.START_TAG &&
                   type != XmlPullParser.END_DOCUMENT) {
           }
           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);
                   }
               }
               // 解析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 (Exception e) {
           throw ie;
       } finally {
           mConstructorArgs[0] = lastContext;
           mConstructorArgs[1] = null;
       }
       return result;
   }
}

上面的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需要完整路徑。可以參考LayoutInflater通過PhoneLayoutInflater創建出來的onCreateView()。

PhoneLayoutInflater類:

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

    protected PhoneLayoutInflater(LayoutInflater original, Context newContext) {
        super(original, newContext);
    }

    @Override protected View onCreateView(String name, AttributeSet attrs) throws ClassNotFoundException {
        for (String prefix : sClassPrefixList) {
            try {
                View view = createView(name, prefix, attrs);
                if (view != null) {
                    return view;
                }
            } catch (ClassNotFoundException e) {
            }
        }

        return super.onCreateView(name, attrs);
    }

    public LayoutInflater cloneInContext(Context newContext) {
        return new PhoneLayoutInflater(this, newContext);
    }
}

onCreateView方法。該方法通過將傳遞過來的View前面加上"android.widget.","android.webkit.","android.app."用來得到該內置View對象的完整路徑,最後根據路徑來創建出對應的View。

接下來看createView(name,prefix,attrs)。

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加入到父視圖中。

 

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