xml转成view【Android】

前端之家收集整理的这篇文章主要介绍了xml转成view【Android】前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

方式一:

View.inflate(context,resource,root);

以下是调用步骤:

View.java -- inflate(Context context,int resource,ViewGroup root)方法

public static View <span style="color:#ff6600;">inflate(Context context,ViewGroup root)</span> {
        LayoutInflater factory = LayoutInflater.from(context);
        return <span style="color:#ff6600;">factory.inflate(resource,root);</span>
    }

LayoutInflater .java -- inflate(int resource,ViewGroup root)方法

public View <span style="color:#ff0000;">inflate(int resource,ViewGroup root)</span> {
        return <span style="color:#ff6600;">inflate(resource,root,root != null);</span>
    }

LayoutInflater .java -- inflate(int resource,ViewGroup root,boolean attachToRoot)方法

public View <span style="color:#ff0000;">inflate(int resource,boolean attachToRoot)</span> {
        if (DEBUG) System.out.println("INFLATING from resource: " + resource);
        XmlResourceParser parser = getContext().getResources().<span style="color:#ff0000;">getLayout(resource);</span>
        try {
            return <span style="color:#ff0000;">inflate(parser,attachToRoot);</span>
        } finally {
            parser.close();
        }
    }

public XmlResourceParser getLayout(int id) throws NotFoundException {
        return loadXmlResourceParser(id,"layout");
    }

LayoutInflater .java -- inflate(int resource,boolean attachToRoot)方法 部分代码:

public View inflate(XmlPullParser parser,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
                }
}


方式二: Activity -- setContentView(int layoutResID)

public void setContentView(int layoutResID) {
        getWindow().setContentView(layoutResID);
        initActionBar();
    }

Window -- public abstract void setContentView(int layoutResID);

实现方法: PhoneWindow -- public void setContentView(int layoutResID)

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();
        }
    }
纵观以上两方式,最终都会调用LayoutInflater .java -- inflate(int resource,boolean attachToRoot) 方法










原文链接:https://www.f2er.com/xml/297930.html

猜你在找的XML相关文章