android重点jar包详解
深入理解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): ernal.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是什么?参看 HYPERLINK "/p/16d156bdfd04" \t "_blank" 这篇文章)不为空:删除 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