Android View解析系列之setContentView和findViewById

概述

话不多说,先上图

Android View解析系列之setContentView和findViewById_第1张图片
未命名文件.png

再看一段熟悉的代码:


    

   public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        TextView textView= (TextView) findViewById(R.id.textview);
        textView.setText("hello world");
    }
}

问题来了:
1.setContentView(@LayoutRes int layoutResID)是如何将布局加载到上图中ContentView上的。
2.findViewById(@IdRes int id)是如何通过id返回View的。

setContentView

跟一下Activity.setContentView
    public void setContentView(@LayoutRes int layoutResID) {
        getWindow().setContentView(layoutResID);//getWindow-->phoneWindow
        initWindowDecorActionBar();//初始化ActionBar
    }
继续跟PhoneWindow.setContentView
public void setContentView(int layoutResID) {
        // Note: FEATURE_CONTENT_TRANSITIONS may be set in the process of installing the window
        // decor, when theme attributes and the like are crystalized. Do not check the feature
        // before this happens.
        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);//最终进入mLayoutInflater.inflate(layoutResID, mContentParent);
        } else {
            mLayoutInflater.inflate(layoutResID, mContentParent);
        }
/************************重点关注***************************/
        mContentParent.requestApplyInsets();
        final Callback cb = getCallback();
        if (cb != null && !isDestroyed()) {
            cb.onContentChanged();
        }
        mContentParentExplicitlySet = true;
    }

直接看重点关注的部分,最终都是走到 mLayoutInflater.inflate(layoutResID, mContentParent),一路跟进去,最终进入到LayoutInflater.rInflate(XmlPullParser parser, View parent, Context context, AttributeSet attrs, boolean finishInflate)

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)) {
                parseViewTag(parser, parent, attrs);
            } else if (TAG_INCLUDE.equals(name)) {
                if (parser.getDepth() == 0) {
                    throw new InflateException(" cannot be the root element");
                }
                parseInclude(parser, context, parent, attrs);
            } else if (TAG_MERGE.equals(name)) {
                throw new InflateException(" must be the root element");
            } 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();
        }
    }

直接看重点关注部分,先跟到rInflateChildren(parser, view, attrs, true)里面

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

看重点关注这句,这里很明显通过递归解析xml,接着往下走,viewGroup.addView(view, params)这一句最终调用的是addView(View child, int index, LayoutParams params)

public void addView(View child, int index, LayoutParams params) {
        if (DBG) {
            System.out.println(this + " addView");
        }

        if (child == null) {
            throw new IllegalArgumentException("Cannot add a null child view to a ViewGroup");
        }

        // addViewInner() will call child.requestLayout() when setting the new LayoutParams
        // therefore, we call requestLayout() on ourselves before, so that the child's request
        // will be blocked at our level
        requestLayout();
        invalidate(true);
        addViewInner(child, index, params, false);
    }

requestLayout(); invalidate(true);这两句会刷新屏幕,将解析好的xml显示到屏幕上面,
到这里第一个问题就解析完了。

findViewById

addViewInner(child, index, params, false)最终会调用ViewGroup.addInArray(child, index)

private void addInArray(View child, int index) {
        View[] children = mChildren;//mChildren:当前ViewGroup子view的数组
        final int count = mChildrenCount;
        final int size = children.length;
        if (index == count) {//待添加View的索引等于mChildren大小
            if (size == count) {//数组满了
                mChildren = new View[size + ARRAY_CAPACITY_INCREMENT];//数组扩容,容量增加12
                System.arraycopy(children, 0, mChildren, 0, size);//旧数组的元素copy到新数组
                children = mChildren;//children指向新数组
            }
            children[mChildrenCount++] = child;//添加子View
        } else if (index < count) {//待添加View的索引小于mChildren大小
            if (size == count) {//数组满了
                mChildren = new View[size + ARRAY_CAPACITY_INCREMENT];//数组扩容,容量增加12
                System.arraycopy(children, 0, mChildren, 0, index);//旧数组的元素copy到新数组
                System.arraycopy(children, index, mChildren, index + 1, count - index);//旧数组的元素copy到新数组
                children = mChildren;//children指向新数组
            } else {
                System.arraycopy(children, index, children, index + 1, count - index);//旧数组的元素copy到新数组
            }
            children[index] = child;//添加子View
            mChildrenCount++;
            if (mLastTouchDownIndex >= index) {
                mLastTouchDownIndex++;
            }
        } else {//待添加View的索引大于mChildren大小
            throw new IndexOutOfBoundsException("index=" + index + " count=" + count);
        }
    }

addInArray(View child, int index)的核心作用是将每个groupView的子view存储到一个数组里面,findViewById将通过id在这个数组中找到对应的view,并返回。直接通过源码去验证

@Nullable
    public View findViewById(@IdRes int id) {
        return getWindow().findViewById(id);
    }

跟一下getWindow

public Window getWindow() {
        return mWindow;
    }

跟一下PhoneWindow.findViewById

public View findViewById(@IdRes int id) {
        return getDecorView().findViewById(id);
    }

跟一下PhoneWindow.getDecorView

public final View getDecorView() {
        if (mDecor == null || mForceDecorInstall) {
            installDecor();
        }
        return mDecor;
    }

private DecorView mDecor;

DecorView是FrameLayout的子类,而FrameLayout是ViewGoup的子类,直接跟ViewGroup的findViewById方法

public final View findViewById(@IdRes int id) {
        if (id < 0) {
            return null;
        }
        return findViewTraversal(id);
    }

继续跟进ViewGroup.findViewTraversal

protected View findViewTraversal(@IdRes int id) {
        if (id == mID) {
            return this;
        }

        final View[] where = mChildren;//mChildren保存了当前ViewGroup的所有子View
        final int len = mChildrenCount;

        for (int i = 0; i < len; i++) {
            View v = where[i];

            if ((v.mPrivateFlags & PFLAG_IS_ROOT_NAMESPACE) == 0) {
                v = v.findViewById(id);

                if (v != null) {
                    return v;
                }
            }
        }

        return null;
    }

注意:这里的mChildren保存了当前ViewGroup的所有子View,就是通过前面我们已经分析的ViewGroup.addInArray方法保存的。也就是说在LayoutInflater.inflate的时候,会调用ViewGroup.addInArray将当前ViewGroup的子View保存到数组中。这里通过一个for循环,取得每个子View,在调用子View.findViewById,继续跟进,最终调用View.findViewTraversal

protected View findViewTraversal(@IdRes int id) {
        if (id == mID) {
            return this;
        }
        return null;
    }

通过当前View对象的id和要找的id对比,如果是,返回当前view,不是,返回null。
OK,第二个问题也就解析完了。

画一张流程图如下所示

Android View解析系列之setContentView和findViewById_第2张图片
setContentView和findViewById.png

你可能感兴趣的:(Android View解析系列之setContentView和findViewById)