Android XML布局與View之間的轉換

Android的布局方式有兩種,一種是通過xml布局,一種是通過java代碼布局,兩種布局方式各有各的好處,當然也可以相互混合使用。很多人都習慣用xml布局,那xml布局是如何轉換成view的呢?本文從源碼的角度來簡單分析下整個過程。

首先,創建一個新的項目,默認生成一個activity,其中xml布局很簡單,就一個RelativeLayout套了一個ImageView,代碼及效果如下:

public class MainActivity extends Activity {  
    @Override  
    protected void onCreate(Bundle savedInstanceState) {  
        super.onCreate(savedInstanceState);  
        setContentView(R.layout.activity_main);  
    }  
 }  
界面1

其中關鍵之處在于調用了父類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實例,那我們直接來看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();  
    }  
}

我們知道每個activity實際都對應一個PhoneWindow,擁有一個頂層的DecorView,DecorView繼承自FrameLayout,作為根View,其中包含了一個標題區域和內容區域,這里的mContentParent就是其內容區域。關于PhoneWindow和DecorView的具體內容,讀者可自行查閱。這段代碼的意思很簡單,如果DecorView的內容區域為null,就先初始化,否則就先把內容區域的子View全部移除,最后再引入layout布局,所以,關鍵在于mLayoutInflater.inflate(layoutResID, mContentParent); 代碼繼續往下看:

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();  
    }  
} 

這里首先根據layout布局文件的Id生成xml資源解析器,然后再調用inflate(parser, root, attachToRoot)生成具體的view。XmlResourceParser是繼承自XmlPullParser和AttributeSet的接口,這里的parser其實是XmlBlock的內部類Parser的實例。

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根節點名:

final String name = parser.getName(); 

第39行根據節點名創建臨時View(temp),這個臨時view(temp)也是xml布局的根view:

View temp = createViewFromTag(name, attrs);  

第61行,在臨時view(temp)的節點下創建所有子View,顯然這個方法里是通過遍歷xml所有子view節點,調用createViewFromTag方法生成子view并加載到根view中:

rInflate(parser, temp, attrs);  

第68到76行,則是判斷,如果inflate方法有父view,則把臨時view(temp)加載到父view中再返回,如果沒有,則直接返回臨時view(temp),我們這里調用inflate方法的時候顯然有父view,即mContentParent,也就是最頂層view DecorView的內容區域。這里最關鍵有兩個方法,一個是createViewFromTag,另一個是rInflate,現在來逐一分析:createViewFromTag實際最終調用的是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;  
    }  
}  

其實這個方法很簡單,就是通過xml節點名,通過反射獲取view的實例再返回,其中先去map中查詢構造函數是否存在,如果存在則直接根據構造函數創建實例,這樣做的好處是不用每次都通過class去獲取構造函數再創建實例,我們看第18行通過類實例獲取構造函數:

constructor = clazz.getConstructor(mConstructorSignature);

其中mConstructorSignature定義如下:

private static final Class[] mConstructorSignature = new Class[] {  
    Context.class, AttributeSet.class};  

很顯然,這里用的是帶有Context和AttributeSet兩個參數的構造函數,這也就是為什么,自定義view一定要重載這個構造函數的原因。最后就是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();  
}  

實這個方法也很簡單,就是通過parser解析xml節點再生成對應View的過程。
XML轉換成View的過程就是這樣了,如有錯誤之處,還望指正,回到本文開頭,其實我們還可以這樣寫:

@Override  
protected void onCreate(Bundle savedInstanceState) {  
    super.onCreate(savedInstanceState);  
    View content = LayoutInflater.from(this).inflate(R.layout.activity_main, null);  
    setContentView(content);  
}
界面2

大家發現問題沒,相較于本文開頭的寫法,后面的灰色布局變成全屏了,我們來看看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>

我明明設置了RelativeLayout的寬度和高度分別為300dip,但為什么全屏了?這是因為layout_width和layout_height是相對于父布局而言的,我們這里inflate的時候設置的父布局為null,所以這個屬性設置也就無效了,指定一個父布局就可以了,例如:

@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);  
}

現在,界面顯示效果就和“界面1”相同了。

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 230,182評論 6 543
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 99,489評論 3 429
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 178,290評論 0 383
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,776評論 1 317
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 72,510評論 6 412
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,866評論 1 328
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,860評論 3 447
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 43,036評論 0 290
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 49,585評論 1 336
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 41,331評論 3 358
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 43,536評論 1 374
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 39,058評論 5 363
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,754評論 3 349
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 35,154評論 0 28
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 36,469評論 1 295
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 52,273評論 3 399
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 48,505評論 2 379

推薦閱讀更多精彩內容