當(dāng)我在Activity的Oncreate中寫了setContentView,都發(fā)生了什么

源碼分析-setContentView都做了些什么

一直以來(lái)只是盲目的寫代碼,然后教程上入門時(shí)候也是告訴你這么做就OK了,有很多東西都不知道為什么,最近正好搞了份6.0的源碼,所以就試著來(lái)分析下之前感覺(jué)迷茫的點(diǎn),本次要探究我們?cè)贏ctivity的Oncreate方法里面調(diào)用setContentView都做了些什么

  • 開(kāi)始之前先說(shuō)下本次用到的工具以及源碼獲取方式,本次主要用到的工具Source Insight
  • 源碼獲取方式:
    1、自己搞個(gè)Linux虛擬機(jī)然后下載,這個(gè)自己可以去搜索相關(guān)教程
    2、福利(需要翻墻),當(dāng)然我下載了是Android6.0的FrameWork層的代碼,如果你要燒錄的話,請(qǐng)參考1

Activity

Activity.java的位置framework\base\core\java\android\app
這里左邊欄搜索setContentView方法可以看到有三個(gè)重載的方法,如下圖

1496208214112.png

這個(gè)三個(gè)方法的代碼結(jié)構(gòu)是這樣子的,相對(duì)源碼略有修改

    public void setContentView(params params...) {
        //調(diào)用Window的方法
        getWindow().setContentView(params);
        //初始化ActionBar
        initWindowDecorActionBar();
    }

PhoneWindow

追查發(fā)現(xiàn)Activity內(nèi)部持有的是一個(gè)private Window mWindow;所以我們接下來(lái)要搜索這個(gè)Window(位置framework\base\core\java\android\view)追查進(jìn)去發(fā)現(xiàn)這個(gè)Window是個(gè)抽象類,那么我們久要找他的實(shí)現(xiàn)類PhoneWindow,接下來(lái)我們就可以查看這個(gè)PhoneWindowsetContentView的方法

    public void setContentView(int layoutResID) {
        ...

        if (hasFeature(FEATURE_CONTENT_TRANSITIONS)) {
            ...
        } else {
            //這里填充布局
            mLayoutInflater.inflate(layoutResID, mContentParent);
        }
        ...
     }

mContentParent

這里可以查看mContentParent的聲明

    // This is the view in which the window contents are placed. It is either
    // mDecor itself, or a child of mDecor where the contents go.
    private ViewGroup mContentParent;

意思大概是這個(gè)ViewGroup就是頂層的Decor或者他包含的要加載的子View(英文比較爛,英文好的童鞋可以自行理解)

LayoutInflater

這段代碼做了一些列的判斷然后調(diào)用了LayoutInflaterinflate方法,繼續(xù)追查L(zhǎng)ayoutInflater.java位于 framework\base\core\java\android\view目錄下,查看inflate方法

    public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
        final Resources res = getContext().getResources();
        //首先獲取Xml布局中書寫的資源
        final XmlResourceParser parser = res.getLayout(resource);
        try {
            //這里做了填充
            return inflate(parser, root, attachToRoot);
        } finally {
            parser.close();
        }
    }

上面這段代碼可以看到主要是兩個(gè)方法

  • res.getlayout用于獲取我們?cè)趚ml中聲明的標(biāo)簽
  • inflate(parser,root,attchToRoot)用于填充布局
    首先我們先看res.getLayout(resource)這個(gè)方法主要用于加載清單文件中的一系列標(biāo)簽體,有興趣可以另行查看,inflate的代碼如下,一下代碼我盡量保留英文注釋方便英文水平比較好的同學(xué)查看
    public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
        synchronized (mConstructorArgs) {
            ...
            View result = root;

            try {
                // Look for the root node.找尋根節(jié)點(diǎn)
                ...
                final String name = parser.;();
                ...
                if (TAG_MERGE.equals(name)) {
                    //如果是merge標(biāo)簽走這里
                    rInflate(parser, root, inflaterContext, attrs, false);
                } else {
                    // Temp is the root view that was found in the xml
                    //temp就是xml文件中的根節(jié)點(diǎn)
                    final View temp = createViewFromTag(root, name, inflaterContext, attrs);

                    ViewGroup.LayoutParams params = null;

                    if (root != null) {
                        // Create layout params that match root, if supplied
                        //找到根節(jié)點(diǎn)的layoutparams
                        params = root.generateLayoutParams(attrs);
                        if (!attachToRoot) {
                            // Set the layout params for temp if we are not
                            // attaching. (If we are, we use addView, below)
                            //講layoutparams交給根節(jié)點(diǎn)的View
                            temp.setLayoutParams(params);
                        }
                    }

                    // Inflate all children under temp against its context.
                    //遍歷跟節(jié)點(diǎn)temp所包涵的子View添加到temp中
                    rInflateChildren(parser, temp, attrs, true);


                    // We are supposed to attach all the views we found (int temp)
                    // to root. Do that now.
                    // root不為空,直接將根節(jié)點(diǎn)View添加到root中
                    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.
                    // root等于null,直接返回根節(jié)點(diǎn)temp
                    if (root == null || !attachToRoot) {
                        result = temp;
                    }
                }

            } catch (Exception e) {
                ...
            } finally {
                // Don't retain static reference on context.
                //釋放資源
                ...
            }


            return result;
        }
    }

上面這段代碼主要有兩個(gè)方法需要注意

  • rInflateChildren(parser, temp, attrs, true)
  • createViewFromTag(root, name, inflaterContext, attrs)
    先看createViewFromTag的代碼
private View createViewFromTag(View parent, String name, Context context, AttributeSet attrs) {
    return createViewFromTag(parent, name, context, attrs, false);
}
    
View createViewFromTag(View parent, String name, Context context, AttributeSet attrs,
            boolean ignoreThemeAttr) {
        ...
        try {
            View view;
            ...
            if (-1 == name.indexOf('.')) {
                 view = onCreateView(parent, name, attrs);
             } else {
                 view = createView(name, null, attrs);
             }
            return view;
        }catch (Exception e) {
            ...
        }
    }

LayoutInflater#createView()

protected View onCreateView(View parent, String name, AttributeSet attrs)
       throws ClassNotFoundException {
   return onCreateView(name, attrs);
}
 
protected View onCreateView(String name, AttributeSet attrs)
        throws ClassNotFoundException {
    return createView(name, "android.view.", attrs);
}
    
private static final HashMap<String, Constructor<? extends View>> sConstructorMap =
        new HashMap<String, Constructor<? extends View>>();

public final View createView(String name, String prefix, AttributeSet attrs)
      throws ClassNotFoundException, InflateException {
      //緩存過(guò)的View的構(gòu)造方法
      Constructor<? extends View> constructor = sConstructorMap.get(name);
      Class<? extends View> clazz = null;

      try {
    
          if (constructor == null) {
              // Class not found in the cache, see if it's real, and try to add it
              //如果沒(méi)有緩存該View的構(gòu)造方法
              clazz = mContext.getClassLoader().loadClass(
                      prefix != null ? (prefix + name) : name).asSubclass(View.class);
              ...
              constructor = clazz.getConstructor(mConstructorSignature);
              constructor.setAccessible(true);
              sConstructorMap.put(name, constructor);
          } else {
              // If we have a filter, apply it to cached constructor
              //如果有緩存的構(gòu)造方法那就使用緩存的
               ...
          }
          //實(shí)例化出View
          final View view = constructor.newInstance(args);
          //ViewStub的懶加載...
          ...
          return view;
    
      }catch (Exception e) {
          ...
      }
}

上面可以看到無(wú)論走那個(gè)分支最終都是會(huì)執(zhí)行createView的,那么這里面用一個(gè)HashMap來(lái)存儲(chǔ)已經(jīng)解析過(guò)的View,如果沒(méi)有解析過(guò)這個(gè)View,那么就直接反射獲取該View的構(gòu)造方法new出來(lái)一個(gè)實(shí)例,這里也可以看出為什么要避免頻繁的inflate操作

LayoutInflater#rInflateChildren

final void rInflateChildren(XmlPullParser parser, View parent, AttributeSet attrs,
        boolean finishInflate) throws XmlPullParserException, IOException {
    rInflate(parser, parent, parent.getContext(), attrs, finishInflate);
}

void rInflate(XmlPullParser parser, View parent, Context context,
        AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {
    //獲取節(jié)點(diǎn)的深度
    final int depth = parser.getDepth();
    int type;
    //循環(huán)遍歷節(jié)點(diǎn)
    while (((type = parser.next()) != XmlPullParser.END_TAG ||
            parser.getDepth() > depth) && type != XmlPullParser.END_DOCUMENT) {
        //跟標(biāo)簽跳過(guò)
        if (type != XmlPullParser.START_TAG) {
            continue;
        }

        final String name = parser.getName();
        
        if (TAG_REQUEST_FOCUS.equals(name)) {
        } else if (TAG_TAG.equals(name)) {
        } else if (TAG_INCLUDE.equals(name)) {
        } else if (TAG_MERGE.equals(name)) {
        } 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();
    }
}

上面代碼可以看出,循環(huán)遍歷每個(gè)節(jié)點(diǎn)的tag,如果是特殊節(jié)點(diǎn)如include、merge那就不去解析View,如果是ImageView、LinearLayout等View的子類那么我就去調(diào)用createViewFromTag實(shí)例化這個(gè)View然后添加到根節(jié)點(diǎn)去,之后再遞歸調(diào)用rInflateChildren去填充下一層級(jí)的ViewGroup,如此反復(fù)直至所有的View都已經(jīng)實(shí)例化并且添加完畢到這里我們就分析完setContentView到底做了些什么,第一次寫源代碼分析有些生疏,大家見(jiàn)諒

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容