我們都知道 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的由來。