android开发:深入理解View(一):从setContentView谈起

我们都知道 MVC,在Android中,这个 V 即指View,那我们今天就来探探View的究竟。

在onCreate方法中,可以调用this.setContentView(layout_id),来设置这个Activity的视图,今天就从setContentView(...)说起吧。

先编写一个简单的Activity:

public class ViewDemoActivity extends Activity {

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

查看父类Activity的setContentView方法:

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

这个getWindow()指向哪里?我们在onCreate中打个log瞧瞧:

D/ViewDemoActivity(3969): com.android.internal.policy.impl.PhoneWindow

原来是PhoneWindow,来看看它的setContentView方法:

    @Override
    public void setContentView(int layoutResID) {
        // 1
        if (mContentParent == null) {
            installDecor();
        } else {
            mContentParent.removeAllViews();
        }

        // 2
        mLayoutInflater.inflate(layoutResID, mContentParent);

        // 3
        final Callback cb = getCallback();
        if (cb != null && !isDestroyed()) {
            cb.onContentChanged();
        }
    }

我们分三步来介绍这个方法:

第一步:判断父容器是否为空

为空:生成Decor; (Decor是什么?参看这篇文章)
不为空:删除 contentParent 所有的子控件。

第二步:解析layoutResID所代表的xml文件

直接看LayoutInflater.inflate(...)方法:

    // 为节省篇幅,删除一些调试代码 
    public View inflate(int resource, ViewGroup root) {
        return inflate(resource, root, root != null);
    }

    public View inflate(int resource, ViewGroup root, boolean attachToRoot) {
        XmlResourceParser parser = getContext().getResources().getLayout(resource);
        try {
            return inflate(parser, root, attachToRoot);
        } finally {
            parser.close();
        }
    }

    public View inflate(XmlPullParser parser, ViewGroup root, boolean attachToRoot) {
        synchronized (mConstructorArgs) {
            final AttributeSet attrs = Xml.asAttributeSet(parser);
            Context lastContext = (Context)mConstructorArgs[0];
            mConstructorArgs[0] = mContext;
            View result = root;

            try {
                // Look for the root node.
                int type;
                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时,root不能为空
                if (TAG_MERGE.equals(name)) {
                    if (root == null || !attachToRoot) {
                        throw new InflateException("<merge /> can be used only with a valid "
                                + "ViewGroup root and attachToRoot=true");
                    }

                    rInflate(parser, root, attrs, false);
                } else {
                    // Temp is the root view that was found in the xml
                    View temp;
                    if (TAG_1995.equals(name)) {
                        temp = new BlinkLayout(mContext, attrs);
                    } else {
                        temp = createViewFromTag(root, name, attrs);
                    }

                    ViewGroup.LayoutParams params = null;

                    if (root != null) {
                        // Create layout params that match root, if supplied
                        params = root.generateLayoutParams(attrs);
                        if (!attachToRoot) {
                            // Set the layout params for temp if we are not attaching. 
                            // (If we are, we use addView, below)
                            temp.setLayoutParams(params);
                        }
                    }

                    // 解析temp的所有子View
                    rInflate(parser, temp, attrs, true);

                    // 将temp添加到root中
                    if (root != null && attachToRoot) {
                        root.addView(temp, params);
                    }

                    // 如果未指定root或者不附加到root,则返回xml所代表的view;
                    if (root == null || !attachToRoot) {
                        result = temp;
                    }
                }
            } catch (XmlPullParserException e) {
                InflateException ex = new InflateException(e.getMessage());
                ex.initCause(e);
                throw ex;
            } catch (IOException e) {
                InflateException ex = new InflateException(parser.getPositionDescription()+ ": " + e.getMessage());
                ex.initCause(e);
                throw ex;
            } finally {
                // Don't retain static reference on context.
                mConstructorArgs[0] = lastContext;
                mConstructorArgs[1] = null;
            }
            return result;
        }
    }

(这几个inflate方法内部的逻辑,请参看注释)
我们注意到,inflate(...)最终会调用rInflate(...),继续挖:

    void rInflate(XmlPullParser parser, View parent, final 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_INCLUDE.equals(name)) {
                if (parser.getDepth() == 0) {
                    throw new InflateException("<include /> cannot be the root element");
                }
                parseInclude(parser, parent, attrs);
            } else if (TAG_MERGE.equals(name)) {
                throw new InflateException("<merge /> must be the root element");
            } else if (TAG_1995.equals(name)) {
                final View view = new BlinkLayout(mContext, attrs);
                final ViewGroup viewGroup = (ViewGroup) parent;
                final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
                rInflate(parser, view, attrs, true);
                viewGroup.addView(view, params);                
            } else {
                final View view = createViewFromTag(parent, name, attrs);
                final ViewGroup viewGroup = (ViewGroup) parent;
                final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
                rInflate(parser, view, attrs, true);
                viewGroup.addView(view, params);
            }
        }

        if (finishInflate) parent.onFinishInflate();
    }

rInflate(...)先特殊处理了几个xml标签

    TAG_MERGE = "merge";    TAG_INCLUDE = "include";    TAG_1995 = "blink";    TAG_REQUEST_FOCUS = "requestFocus";

然后在else分支,会 递归 调用rInflate(...),将xml的子控件添加到parent中,生成完整的 contentView
看了这里,同学们就会明白,为什么不建议在布局文件中做过多地View嵌套了吧,层层递归啊:(

第三步:通知Callback,ContentView发生改变

这个getCallback()是什么?打个Log看看:

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        super.setContentView(R.layout.view_demo);
        Log.d("ViewDemo", getWindow().getCallback().toString());
    }

输出结果为:

D/ViewDemoActivity( 7228): cn.erhu.android.view.ViewDemoActivity@6562f2c0

这不就是ViewDemoActivity吗?
在Activity.java中,我们在attach()方法中发现了蛛丝马迹:

    final void attach(...) {
        ...
        mWindow = PolicyManager.makeNewWindow(this);
        mWindow.setCallback(this);
        ...
    }
    public void onContentChanged() {
    }

我们发现原来PhoneWindow的callback原来就是Activity,并且Activity的onContentChanged()方法是空的,所以我们可以在自己的Activity中重写这个方法,来监听ContentView发生改变的事件。

OK,setContentView()大体就是这么回事,下面再补充几个知识点。


补充知识点

1、PhoneWindows的mLayoutInflater是哪里来的?

PhoneWindow.java

public PhoneWindow(Context context) {
    super(context);
    mLayoutInflater = LayoutInflater.from(context);
}

LayoutInflater.java

public static LayoutInflater from(Context context) {
    LayoutInflater LayoutInflater =
            (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    if (LayoutInflater == null) {
        throw new AssertionError("LayoutInflater not found.");
    }
    return LayoutInflater;
}

ContextImpl.java

@Override
public Object getSystemService(String name) {
    ServiceFetcher fetcher = SYSTEM_SERVICE_MAP.get(name);
    return fetcher == null ? null : fetcher.getService(this);
}
private static void registerService(String serviceName, ServiceFetcher fetcher) {
    if (!(fetcher instanceof StaticServiceFetcher)) {
        fetcher.mContextCacheIndex = sNextPerContextServiceCacheIndex++;
    }
    SYSTEM_SERVICE_MAP.put(serviceName, fetcher);
}
static {
    ...
    registerService(LAYOUT_INFLATER_SERVICE, new ServiceFetcher() {
            public Object createService(ContextImpl ctx) {
                return PolicyManager.makeNewLayoutInflater(ctx.getOuterContext());
            }});
    ...
}

原来,mLayoutInflater是ContextImpl.java在加载的时候,调用PolicyManager.makeNewLayoutInflater生成的

PoliceManager.java

    private static final String POLICY_IMPL_CLASS_NAME = "com.android.internal.policy.impl.Policy";
    private static final IPolicy sPolicy;

    static {
        // Pull in the actual implementation of the policy at run-time
        try {
            Class policyClass = Class.forName(POLICY_IMPL_CLASS_NAME);
            sPolicy = (IPolicy)policyClass.newInstance();
            ...
    }
    public static LayoutInflater makeNewLayoutInflater(Context context) {
        return sPolicy.makeNewLayoutInflater(context);
    }

最终定位到Policy.java

    public LayoutInflater makeNewLayoutInflater(Context context) {
        return new PhoneLayoutInflater(context);
    }

mLayoutInflater是一个PhoneLayoutInflater,这便是mInflaterLayout的由来。

posted @ 2016-01-07 13:26  one_person  阅读(266)  评论(0编辑  收藏  举报