Android 關(guān)于XmlResourceParser

我們先看看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ù)深度的定義糯钙,


image

獲取到該布局文件的深度為:


我們可以看到,深度是從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)該知道了吧?

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末狡刘,一起剝皮案震驚了整個(gè)濱河市享潜,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌嗅蔬,老刑警劉巖剑按,帶你破解...
    沈念sama閱讀 219,539評(píng)論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異澜术,居然都是意外死亡艺蝴,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,594評(píng)論 3 396
  • 文/潘曉璐 我一進(jìn)店門鸟废,熙熙樓的掌柜王于貴愁眉苦臉地迎上來猜敢,“玉大人,你說我怎么就攤上這事盒延÷嘀Γ” “怎么了?”我有些...
    開封第一講書人閱讀 165,871評(píng)論 0 356
  • 文/不壞的土叔 我叫張陵兰英,是天一觀的道長。 經(jīng)常有香客問我供鸠,道長畦贸,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 58,963評(píng)論 1 295
  • 正文 為了忘掉前任楞捂,我火速辦了婚禮薄坏,結(jié)果婚禮上,老公的妹妹穿的比我還像新娘寨闹。我一直安慰自己胶坠,他們只是感情好,可當(dāng)我...
    茶點(diǎn)故事閱讀 67,984評(píng)論 6 393
  • 文/花漫 我一把揭開白布繁堡。 她就那樣靜靜地躺著沈善,像睡著了一般乡数。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上闻牡,一...
    開封第一講書人閱讀 51,763評(píng)論 1 307
  • 那天净赴,我揣著相機(jī)與錄音,去河邊找鬼罩润。 笑死玖翅,一個(gè)胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的割以。 我是一名探鬼主播金度,決...
    沈念sama閱讀 40,468評(píng)論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼严沥!你這毒婦竟也來了猜极?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,357評(píng)論 0 276
  • 序言:老撾萬榮一對情侶失蹤祝峻,失蹤者是張志新(化名)和其女友劉穎魔吐,沒想到半個(gè)月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體莱找,經(jīng)...
    沈念sama閱讀 45,850評(píng)論 1 317
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡酬姆,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 38,002評(píng)論 3 338
  • 正文 我和宋清朗相戀三年,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了奥溺。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片辞色。...
    茶點(diǎn)故事閱讀 40,144評(píng)論 1 351
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡,死狀恐怖浮定,靈堂內(nèi)的尸體忽然破棺而出相满,到底是詐尸還是另有隱情,我是刑警寧澤桦卒,帶...
    沈念sama閱讀 35,823評(píng)論 5 346
  • 正文 年R本政府宣布立美,位于F島的核電站,受9級(jí)特大地震影響方灾,放射性物質(zhì)發(fā)生泄漏建蹄。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 41,483評(píng)論 3 331
  • 文/蒙蒙 一裕偿、第九天 我趴在偏房一處隱蔽的房頂上張望洞慎。 院中可真熱鬧,春花似錦嘿棘、人聲如沸劲腿。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,026評(píng)論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽焦人。三九已至挥吵,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間垃瞧,已是汗流浹背蔫劣。 一陣腳步聲響...
    開封第一講書人閱讀 33,150評(píng)論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留个从,地道東北人脉幢。 一個(gè)月前我還...
    沈念sama閱讀 48,415評(píng)論 3 373
  • 正文 我出身青樓,卻偏偏與公主長得像嗦锐,于是被迫代替她去往敵國和親嫌松。 傳聞我的和親對象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 45,092評(píng)論 2 355

推薦閱讀更多精彩內(nèi)容

  • 綜述 在aapt編譯apk的過程中奕污,aapt中的XMLNode類會(huì)將資源生成一個(gè)ResXMLTree對象萎羔,并將其序...
    Jtag特工閱讀 2,135評(píng)論 1 3
  • 備注: 本篇文章所引用的源碼版本:android-sdk-21 轉(zhuǎn)載請注明出處:http://blog.csdn....
    良秋閱讀 2,385評(píng)論 3 15
  • 一、簡歷準(zhǔn)備 1碳默、個(gè)人技能 (1)自定義控件贾陷、UI設(shè)計(jì)、常用動(dòng)畫特效 自定義控件 ①為什么要自定義控件嘱根? Andr...
    lucas777閱讀 5,213評(píng)論 2 54
  • 前言 AttributeSet與XmlPullParser這2個(gè)接口在解析xml文件時(shí)經(jīng)常配合使用该抒,二者可進(jìn)行相互...
    GrayMonkey閱讀 1,973評(píng)論 2 6
  • 2012年夏季慌洪,我誤打誤撞,在現(xiàn)在已是江北新區(qū)范圍內(nèi)的某小區(qū)買了一套極具升值潛力的房子凑保。去年房價(jià)最高的時(shí)候冈爹,...
    jinlinglq閱讀 228評(píng)論 0 0