Android的布局方式有兩種,一種是通過(guò)xml布局姑隅,一種是通過(guò)java代碼布局伞梯,兩種布局方式各有各的好處玫氢,當(dāng)然也可以相互混合使用。很多人都習(xí)慣用xml布局谜诫,那xml布局是如何轉(zhuǎn)換成view的呢漾峡?本文從源碼的角度來(lái)簡(jiǎn)單分析下整個(gè)過(guò)程。
首先喻旷,創(chuàng)建一個(gè)新的項(xiàng)目生逸,默認(rèn)生成一個(gè)activity,其中xml布局很簡(jiǎn)單,就一個(gè)RelativeLayout套了一個(gè)ImageView槽袄,代碼及效果如下:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}
其中關(guān)鍵之處在于調(diào)用了父類Activity的setContentView方法:
/**
* Set the activity content from a layout resource. The resource will be
* inflated, adding all top-level views to the activity.
*
* @param layoutResID Resource ID to be inflated.
*/
public void setContentView(int layoutResID) {
getWindow().setContentView(layoutResID);
}
getWindow返回的是PhoneWindow實(shí)例烙无,那我們直接來(lái)看PhoneWindow中的setContentView方法:
@Override
public void setContentView(int layoutResID) {
if (mContentParent == null) {
installDecor();
} else {
mContentParent.removeAllViews();
}
mLayoutInflater.inflate(layoutResID, mContentParent);
final Callback cb = getCallback();
if (cb != null) {
cb.onContentChanged();
}
}
我們知道每個(gè)activity實(shí)際都對(duì)應(yīng)一個(gè)PhoneWindow,擁有一個(gè)頂層的DecorView遍尺,DecorView繼承自FrameLayout截酷,作為根View,其中包含了一個(gè)標(biāo)題區(qū)域和內(nèi)容區(qū)域乾戏,這里的mContentParent就是其內(nèi)容區(qū)域迂苛。關(guān)于PhoneWindow和DecorView的具體內(nèi)容,讀者可自行查閱鼓择。這段代碼的意思很簡(jiǎn)單三幻,如果DecorView的內(nèi)容區(qū)域?yàn)閚ull,就先初始化惯退,否則就先把內(nèi)容區(qū)域的子View全部移除赌髓,最后再引入layout布局,所以催跪,關(guān)鍵在于mLayoutInflater.inflate(layoutResID, mContentParent); 代碼繼續(xù)往下看:
public View inflate(int resource, ViewGroup root) {
return inflate(resource, root, root != null);
}
public View inflate(int resource, ViewGroup root, boolean attachToRoot) {
if (DEBUG) System.out.println("INFLATING from resource: " + resource);
XmlResourceParser parser = getContext().getResources().getLayout(resource);
try {
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}
這里首先根據(jù)layout布局文件的Id生成xml資源解析器锁蠕,然后再調(diào)用inflate(parser, root, attachToRoot)生成具體的view。XmlResourceParser是繼承自XmlPullParser和AttributeSet的接口懊蒸,這里的parser其實(shí)是XmlBlock的內(nèi)部類Parser的實(shí)例荣倾。
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();
if (DEBUG) {
System.out.println("**************************");
System.out.println("Creating root view: "
+ name);
System.out.println("**************************");
}
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);
} else {
// Temp is the root view that was found in the xml
View temp = createViewFromTag(name, attrs);
ViewGroup.LayoutParams params = null;
if (root != null) {
if (DEBUG) {
System.out.println("Creating params from root: " +
root);
}
// 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);
}
}
if (DEBUG) {
System.out.println("-----> start inflating children");
}
// Inflate all children under temp
rInflate(parser, temp, attrs);
if (DEBUG) {
System.out.println("-----> done inflating children");
}
// We are supposed to attach all the views we found (int temp)
// to root. Do that now.
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.
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;
}
}
第21行,獲取xml根節(jié)點(diǎn)名:
final String name = parser.getName();
第39行根據(jù)節(jié)點(diǎn)名創(chuàng)建臨時(shí)View(temp)骑丸,這個(gè)臨時(shí)view(temp)也是xml布局的根view:
View temp = createViewFromTag(name, attrs);
第61行舌仍,在臨時(shí)view(temp)的節(jié)點(diǎn)下創(chuàng)建所有子View,顯然這個(gè)方法里是通過(guò)遍歷xml所有子view節(jié)點(diǎn)通危,調(diào)用createViewFromTag方法生成子view并加載到根view中:
rInflate(parser, temp, attrs);
第68到76行铸豁,則是判斷,如果inflate方法有父view菊碟,則把臨時(shí)view(temp)加載到父view中再返回节芥,如果沒(méi)有,則直接返回臨時(shí)view(temp)逆害,我們這里調(diào)用inflate方法的時(shí)候顯然有父view头镊,即mContentParent,也就是最頂層view DecorView的內(nèi)容區(qū)域魄幕。這里最關(guān)鍵有兩個(gè)方法相艇,一個(gè)是createViewFromTag,另一個(gè)是rInflate纯陨,現(xiàn)在來(lái)逐一分析:createViewFromTag實(shí)際最終調(diào)用的是createView方法:
public final View createView(String name, String prefix, AttributeSet attrs)
throws ClassNotFoundException, InflateException {
Constructor constructor = sConstructorMap.get(name);
Class clazz = null;
try {
if (constructor == null) {
// Class not found in the cache, see if it's real, and try to add it
clazz = mContext.getClassLoader().loadClass(
prefix != null ? (prefix + name) : name);
if (mFilter != null && clazz != null) {
boolean allowed = mFilter.onLoadClass(clazz);
if (!allowed) {
failNotAllowed(name, prefix, attrs);
}
}
constructor = clazz.getConstructor(mConstructorSignature);
sConstructorMap.put(name, constructor);
} else {
// If we have a filter, apply it to cached constructor
if (mFilter != null) {
// Have we seen this name before?
Boolean allowedState = mFilterMap.get(name);
if (allowedState == null) {
// New class -- remember whether it is allowed
clazz = mContext.getClassLoader().loadClass(
prefix != null ? (prefix + name) : name);
boolean allowed = clazz != null && mFilter.onLoadClass(clazz);
mFilterMap.put(name, allowed);
if (!allowed) {
failNotAllowed(name, prefix, attrs);
}
} else if (allowedState.equals(Boolean.FALSE)) {
failNotAllowed(name, prefix, attrs);
}
}
}
Object[] args = mConstructorArgs;
args[1] = attrs;
return (View) constructor.newInstance(args);
} catch (NoSuchMethodException e) {
InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Error inflating class "
+ (prefix != null ? (prefix + name) : name));
ie.initCause(e);
throw ie;
} catch (ClassNotFoundException e) {
// If loadClass fails, we should propagate the exception.
throw e;
} catch (Exception e) {
InflateException ie = new InflateException(attrs.getPositionDescription()
+ ": Error inflating class "
+ (clazz == null ? "<unknown>" : clazz.getName()));
ie.initCause(e);
throw ie;
}
}
其實(shí)這個(gè)方法很簡(jiǎn)單坛芽,就是通過(guò)xml節(jié)點(diǎn)名留储,通過(guò)反射獲取view的實(shí)例再返回,其中先去map中查詢構(gòu)造函數(shù)是否存在靡馁,如果存在則直接根據(jù)構(gòu)造函數(shù)創(chuàng)建實(shí)例欲鹏,這樣做的好處是不用每次都通過(guò)class去獲取構(gòu)造函數(shù)再創(chuàng)建實(shí)例,我們看第18行通過(guò)類實(shí)例獲取構(gòu)造函數(shù):
constructor = clazz.getConstructor(mConstructorSignature);
其中mConstructorSignature定義如下:
private static final Class[] mConstructorSignature = new Class[] {
Context.class, AttributeSet.class};
很顯然臭墨,這里用的是帶有Context和AttributeSet兩個(gè)參數(shù)的構(gòu)造函數(shù)赔嚎,這也就是為什么,自定義view一定要重載這個(gè)構(gòu)造函數(shù)的原因胧弛。最后就是rInflate方法:
private void rInflate(XmlPullParser parser, View parent, final AttributeSet attrs)
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 {
final View view = createViewFromTag(name, attrs);
final ViewGroup viewGroup = (ViewGroup) parent;
final ViewGroup.LayoutParams params = viewGroup.generateLayoutParams(attrs);
rInflate(parser, view, attrs);
viewGroup.addView(view, params);
}
}
parent.onFinishInflate();
}
實(shí)這個(gè)方法也很簡(jiǎn)單尤误,就是通過(guò)parser解析xml節(jié)點(diǎn)再生成對(duì)應(yīng)View的過(guò)程。
XML轉(zhuǎn)換成View的過(guò)程就是這樣了结缚,如有錯(cuò)誤之處损晤,還望指正,回到本文開(kāi)頭红竭,其實(shí)我們還可以這樣寫(xiě):
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
View content = LayoutInflater.from(this).inflate(R.layout.activity_main, null);
setContentView(content);
}
大家發(fā)現(xiàn)問(wèn)題沒(méi)尤勋,相較于本文開(kāi)頭的寫(xiě)法,后面的灰色布局變成全屏了茵宪,我們來(lái)看看xml代碼:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="300dip"
android:layout_height="300dip"
android:background="#888888"
tools:context=".MainActivity" >
<ImageView
android:layout_width="200dip"
android:layout_height="200dip"
android:background="#238712"
android:contentDescription="@null" />
</RelativeLayout>
我明明設(shè)置了RelativeLayout的寬度和高度分別為300dip最冰,但為什么全屏了?這是因?yàn)閘ayout_width和layout_height是相對(duì)于父布局而言的稀火,我們這里inflate的時(shí)候設(shè)置的父布局為null暖哨,所以這個(gè)屬性設(shè)置也就無(wú)效了,指定一個(gè)父布局就可以了凰狞,例如:
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
RelativeLayout rootView = new RelativeLayout(this);
View content = LayoutInflater.from(this).inflate(R.layout.activity_main, rootView);
setContentView(content);
}
現(xiàn)在篇裁,界面顯示效果就和“界面1”相同了。