我們先看看XmlResourceParser 類:
/**
* The XML parsing interface returned for an XML resource. This is a standard
* XmlPullParser interface, as well as an extended AttributeSet interface and
* an additional close() method on this interface for the client to indicate
* when it is done reading the resource.
*/
public interface XmlResourceParser extends XmlPullParser, AttributeSet, AutoCloseable {
/**
* Close this interface to the resource. Calls on the interface are no
* longer value after this call.
*/
public void close();
}
該類的解釋為:
為XML資源返回的XML解析接口捏雌,這是一個(gè)標(biāo)準(zhǔn)XmlPullParser接口崔涂,同時(shí)繼承AttributeSet接口以及當(dāng)用戶完成資源讀取時(shí)調(diào)用的close接口,簡單來說就是一個(gè)xml資源解析器,用于解析xml資源。
那么該類的作用是什么?
我們知道Activity的setContentView()其實(shí)調(diào)用的是PhoneWindow里面的setContentView
@Override
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);
} else {
mLayoutInflater.inflate(layoutResID, mContentParent);
}
mContentParent.requestApplyInsets();
final Callback cb = getCallback();
if (cb != null && !isDestroyed()) {
cb.onContentChanged();
}
mContentParentExplicitlySet = true;
}
@Override
public void setContentView(View view) {
setContentView(view, new ViewGroup.LayoutParams(MATCH_PARENT, MATCH_PARENT));
}
我們可以看到接口
mLayoutInflater.inflate(layoutResID, mContentParent);
將activity傳遞進(jìn)來的layoutResID即布局ID榕茧,加載到mContentParent里面去。
接著我們進(jìn)到LayoutInflater的inflate接口可以看到
public View inflate(@LayoutRes int resource, @Nullable ViewGroup root, boolean attachToRoot) {
final Resources res = getContext().getResources();
if (DEBUG) {
Log.d(TAG, "INFLATING from resource: \"" + res.getResourceName(resource) + "\" ("
+ Integer.toHexString(resource) + ")");
}
final XmlResourceParser parser = res.getLayout(resource);
try {
return inflate(parser, root, attachToRoot);
} finally {
parser.close();
}
}
里面調(diào)用了一個(gè):
final XmlResourceParser parser = res.getLayout(resource);
并且再通過
public View inflate(XmlPullParser parser, @Nullable ViewGroup root, boolean attachToRoot) {
synchronized (mConstructorArgs) {
Trace.traceBegin(Trace.TRACE_TAG_VIEW, "inflate");
final Context inflaterContext = mContext;
final AttributeSet attrs = Xml.asAttributeSet(parser);
Context lastContext = (Context) mConstructorArgs[0];
mConstructorArgs[0] = inflaterContext;
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, inflaterContext, attrs, false);
} else {
// Temp is the root view that was found in the xml
final View temp = createViewFromTag(root, name, inflaterContext, 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 against its context.
rInflateChildren(parser, temp, attrs, true);
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) {
final InflateException ie = new InflateException(e.getMessage(), e);
ie.setStackTrace(EMPTY_STACK_TRACE);
throw ie;
} catch (Exception e) {
final InflateException ie = new InflateException(parser.getPositionDescription()
+ ": " + e.getMessage(), e);
ie.setStackTrace(EMPTY_STACK_TRACE);
throw ie;
} finally {
// Don't retain static reference on context.
mConstructorArgs[0] = lastContext;
mConstructorArgs[1] = null;
Trace.traceEnd(Trace.TRACE_TAG_VIEW);
}
return result;
}
}
返回view
這里最終會(huì)走到一個(gè)方法客给,在這個(gè)方法里面進(jìn)行處理
void rInflate(XmlPullParser parser, View parent, Context context,
AttributeSet attrs, boolean finishInflate) throws XmlPullParserException, IOException {
final int depth = parser.getDepth();
int type;
boolean pendingRequestFocus = false;
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)) {
pendingRequestFocus = true;
consumeChildElements(parser);
} else if (TAG_TAG.equals(name)) {
parseViewTag(parser, parent, attrs);
} else if (TAG_INCLUDE.equals(name)) {
if (parser.getDepth() == 0) {
throw new InflateException("<include /> cannot be the root element");
}
parseInclude(parser, context, parent, attrs);
} else if (TAG_MERGE.equals(name)) {
throw new InflateException("<merge /> 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 (pendingRequestFocus) {
parent.restoreDefaultFocus();
}
if (finishInflate) {
parent.onFinishInflate();
}
}
我們知道XmlPullParser是安卓內(nèi)置的一個(gè)XML解析器用押,用于解析XML文件,同時(shí)我們的布局文件也是一種XML格式文件靶剑,通過XmlPullParser解析整個(gè)布局文件蜻拨,解析其中定義的View,例如LinearLayout和FrameLayout等等桩引,再通過AttributeSet attrs = Xml.asAttributeSet(parser)來獲取view定義的屬性缎讼,并通過createViewFromTag()方法來創(chuàng)建View的實(shí)例,且在每次遞歸完成的時(shí)候?qū)⑦@個(gè)View添加到父布局中去坑匠。
好了血崭,我們粗略過了一遍布局文件的加載過程了,我們由此可大概知道厘灼,XmlResourcePareser主要用于解析安卓中的資源文件夹纫,例如布局資源文件(layout.xml),動(dòng)畫資源文件(anim.xml)等資源文件手幢,由于其繼承XmlPullParser捷凄,AttributeSet,因此其同時(shí)具有解析xml布局文件和操作xml中定義的屬性的作用围来。
我們打開android.content.res.Resources類查看跺涤,其中有以下方法用于獲取XmlResourceParser
public XmlResourceParser getLayout(@LayoutRes int id) throws NotFoundException {
return loadXmlResourceParser(id, "layout");
}
public XmlResourceParser getAnimation(@AnimatorRes @AnimRes int id) throws NotFoundException {
return loadXmlResourceParser(id, "anim");
}
public XmlResourceParser getXml(@XmlRes int id) throws NotFoundException {
return loadXmlResourceParser(id, "xml");
}
開始寫代碼之前我們先了解一些相關(guān)的常量和方法:
- int START_DOCUMENT = 0 :文檔的最開頭匈睁,尚未讀取任何內(nèi)容
- int END_DOCUMENT = 1 :到達(dá)文檔的末尾
- int START_TAG = 2 :開始解析標(biāo)簽
- int END_TAG = 3 :結(jié)束解析標(biāo)簽
- int TEXT = 4 :讀取字符數(shù)據(jù),通過調(diào)用getText()可以獲得
- int getDepth() :返回元素的當(dāng)前深度
- int getEventType() :返回當(dāng)前事件的類型(START_TAG桶错,END_TAG航唆,TEXT等)
- int next() :獲取下一個(gè)解析事件
- String getAttributeName (int index) :返回指定屬性的本地名稱
- String getName() :返回
我們主要講解以下接口:
public XmlResourceParser getLayout(@LayoutRes int id)
顧名思義,根據(jù)提供的布局資源文件id返回一個(gè)可讀取布局文件中view相關(guān)屬性的XmlResourceParser院刁。
我們先定義一個(gè)layout文件:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:background="#66000000"
android:layout_width="800dp"
android:layout_height="800dp"
tools:context=".MainActivity">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/iv3"
android:layout_width="300dp"
android:layout_height="300dp" />
</RelativeLayout>
<ImageView
android:id="@+id/iv2"
android:layout_width="200dp"
android:layout_height="200dp" />
</RelativeLayout>
<ImageView
android:id="@+id/iv1"
android:layout_width="100dp"
android:layout_height="100dp" />
</RelativeLayout>
</RelativeLayout>
主要代碼為:
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
XLog.configure().setLogHeadEnable(false);
XmlResourceParser parser = getResources().getLayout(R.layout.activity_main);
try {
int type;
//過濾掉END_DOCUMENT和非START_TAG的事件
while ((type = parser.next())!= XmlPullParser.END_DOCUMENT ) {
if (type != XmlPullParser.START_TAG){
continue;
}
StringBuilder stringBuilder = new StringBuilder()
.append("current type: ")
.append(getType(type))
.append("\n")
.append("current depth: ")
.append(parser.getDepth())
.append("\n")
.append("current name: ")
.append(parser.getName())
.append("\n");
for (int i = 0; i < parser.getAttributeCount(); i++){
stringBuilder.append(String.format("第%d個(gè)屬性 -> ", i+1))
.append(parser.getAttributeName(i))
.append(" : ")
.append(parser.getAttributeValue(i))
.append("\n");
}
XLog.e(stringBuilder.toString());
}
}catch (IOException e){
e.printStackTrace();
} catch (XmlPullParserException e) {
e.printStackTrace();
} finally {
parser.close();
}
}
private String getType(int type){
switch (type){
case XmlPullParser.START_DOCUMENT:
return "START_DOCUMENT";
case XmlPullParser.END_DOCUMENT:
return "END_DOCUMENT";
case XmlPullParser.START_TAG:
return "START_TAG";
case XmlPullParser.END_TAG:
return "END_TAG";
}
return String.valueOf(type);
}
}
我們根據(jù)深度的定義糯钙,
獲取到該布局文件的深度為:
我們可以看到,深度是從1開始的退腥。
所有的log為:
┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────
│ current type: START_TAG
│ current depth: 1
│ current name: RelativeLayout
│ 第1個(gè)屬性 -> background : #66000000
│ 第2個(gè)屬性 -> layout_width : 800.0dip
│ 第3個(gè)屬性 -> layout_height : 800.0dip
└────────────────────────────────────────────────────────────────────────────────────────────────────────────────
┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────
│ current type: START_TAG
│ current depth: 2
│ current name: RelativeLayout
│ 第1個(gè)屬性 -> layout_width : -1
│ 第2個(gè)屬性 -> layout_height : -1
└────────────────────────────────────────────────────────────────────────────────────────────────────────────────
┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────
│ current type: START_TAG
│ current depth: 3
│ current name: RelativeLayout
│ 第1個(gè)屬性 -> layout_width : -1
│ 第2個(gè)屬性 -> layout_height : -1
└────────────────────────────────────────────────────────────────────────────────────────────────────────────────
┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────
│ current type: START_TAG
│ current depth: 4
│ current name: ImageView
│ 第1個(gè)屬性 -> id : @2131165256
│ 第2個(gè)屬性 -> layout_width : 300.0dip
│ 第3個(gè)屬性 -> layout_height : 300.0dip
└────────────────────────────────────────────────────────────────────────────────────────────────────────────────
┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────
│ current type: START_TAG
│ current depth: 3
│ current name: ImageView
│ 第1個(gè)屬性 -> id : @2131165255
│ 第2個(gè)屬性 -> layout_width : 200.0dip
│ 第3個(gè)屬性 -> layout_height : 200.0dip
└────────────────────────────────────────────────────────────────────────────────────────────────────────────────
┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────
│ current type: START_TAG
│ current depth: 2
│ current name: ImageView
│ 第1個(gè)屬性 -> id : @2131165254
│ 第2個(gè)屬性 -> layout_width : 100.0dip
│ 第3個(gè)屬性 -> layout_height : 100.0dip
└────────────────────────────────────────────────────────────────────────────────────────────────────────────────
回到問題
那么該類的作用是什么任岸?
你應(yīng)該知道了吧?