Android 关于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解析接口,这是一个标准XmlPullParser接口,同时继承AttributeSet接口以及当用户完成资源读取时调用的close接口,简单来说就是一个xml资源解析器,用于解析xml资源。



那么该类的作用是什么?

我们知道Activity的setContentView()其实调用的是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传递进来的layoutResID即布局ID,加载到mContentParent里面去。

接着我们进到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();
        }
    }

里面调用了一个:

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(" 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

这里最终会走到一个方法,在这个方法里面进行处理

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(" cannot be the root element");
                }
                parseInclude(parser, context, parent, attrs);
            } else if (TAG_MERGE.equals(name)) {
                throw new InflateException(" 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是安卓内置的一个XML解析器,用于解析XML文件,同时我们的布局文件也是一种XML格式文件,通过XmlPullParser解析整个布局文件,解析其中定义的View,例如LinearLayout和FrameLayout等等,再通过AttributeSet attrs = Xml.asAttributeSet(parser)来获取view定义的属性,并通过createViewFromTag()方法来创建View的实例,且在每次递归完成的时候将这个View添加到父布局中去。


好了,我们粗略过了一遍布局文件的加载过程了,我们由此可大概知道,XmlResourcePareser主要用于解析安卓中的资源文件,例如布局资源文件(layout.xml),动画资源文件(anim.xml)等资源文件,由于其继承XmlPullParser,AttributeSet,因此其同时具有解析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");
    }

开始写代码之前我们先了解一些相关的常量和方法:

  • int START_DOCUMENT = 0 :文档的最开头,尚未读取任何内容
  • int END_DOCUMENT = 1 :到达文档的末尾
  • int START_TAG = 2 :开始解析标签
  • int END_TAG = 3 :结束解析标签
  • int TEXT = 4 :读取字符数据,通过调用getText()可以获得
  • int getDepth() :返回元素的当前深度
  • int getEventType() :返回当前事件的类型(START_TAG,END_TAG,TEXT等)
  • int next() :获取下一个解析事件
  • String getAttributeName (int index) :返回指定属性的本地名称
  • String getName() :返回

我们主要讲解以下接口:

public XmlResourceParser getLayout(@LayoutRes int id)

顾名思义,根据提供的布局资源文件id返回一个可读取布局文件中view相关属性的XmlResourceParser。

我们先定义一个layout文件:


<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个属性 -> ", 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);
    }

}

我们根据深度的定义,
Android 关于XmlResourceParser_第1张图片

获取到该布局文件的深度为:
Android 关于XmlResourceParser_第2张图片

我们可以看到,深度是从1开始的。

Android 关于XmlResourceParser_第3张图片

所有的log为:


    ┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────
    │ current type: START_TAG
    │ current depth: 1
    │ current name: RelativeLayout
    │ 第1个属性 -> background : #66000000
    │ 第2个属性 -> layout_width : 800.0dip
    │ 第3个属性 -> layout_height : 800.0dip
    └────────────────────────────────────────────────────────────────────────────────────────────────────────────────

    ┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────
    │ current type: START_TAG
    │ current depth: 2
    │ current name: RelativeLayout
    │ 第1个属性 -> layout_width : -1
    │ 第2个属性 -> layout_height : -1
    └────────────────────────────────────────────────────────────────────────────────────────────────────────────────

    ┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────
    │ current type: START_TAG
    │ current depth: 3
    │ current name: RelativeLayout
    │ 第1个属性 -> layout_width : -1
    │ 第2个属性 -> layout_height : -1
    └────────────────────────────────────────────────────────────────────────────────────────────────────────────────

    ┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────
    │ current type: START_TAG
    │ current depth: 4
    │ current name: ImageView
    │ 第1个属性 -> id : @2131165256
    │ 第2个属性 -> layout_width : 300.0dip
    │ 第3个属性 -> layout_height : 300.0dip
    └────────────────────────────────────────────────────────────────────────────────────────────────────────────────

    ┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────
    │ current type: START_TAG
    │ current depth: 3
    │ current name: ImageView
    │ 第1个属性 -> id : @2131165255
    │ 第2个属性 -> layout_width : 200.0dip
    │ 第3个属性 -> layout_height : 200.0dip
    └────────────────────────────────────────────────────────────────────────────────────────────────────────────────

    ┌────────────────────────────────────────────────────────────────────────────────────────────────────────────────
    │ current type: START_TAG
    │ current depth: 2
    │ current name: ImageView
    │ 第1个属性 -> id : @2131165254
    │ 第2个属性 -> layout_width : 100.0dip
    │ 第3个属性 -> layout_height : 100.0dip
    └────────────────────────────────────────────────────────────────────────────────────────────────────────────────

回到问题
那么该类的作用是什么?
你应该知道了吧?

你可能感兴趣的:(android)