LayoutInflater inflate參數詳解

LayoutInflater

類概述:html

實例化一個XML佈局文件到相應的View對象,並不直接使用。使用getLayoutInflater()或getSystemService(String)來獲取一個標準的佈局填充器實例。能夠勾子到當前的View對象,配置到您當前運行的設備上。android

public View inflate (int resource, ViewGroup root, boolean attachToRoot)

把指定的資源XML填充到一個分層的View對象中,若是發生錯誤,則拋出InflateException異常web

參數解釋:佈局

resource:加載的XMl佈局資源IDthis

root:生成的分層視圖的父對象(若是attachToRoot爲true),或者是一個簡單的提供了一系列佈局參數生成的Veiw對象(若是attachToRoot爲false)spa

attachToRoot:是否要填充的分層視圖要添加到父對象中,若是爲false。ROOT內容僅僅是初始化,若是要使用,仍須要手動添加。.net

舉例:xml

舉個例子看一下htm

新建一個工程對象

工程包含兩個xml文件

layout/main.xml

<?xml version=」1.0″ encoding=」utf-8″?>

<LinearLayout xmlns:android=」http://schemas.android.com/apk/res/android」

    android:layout_width=」fill_parent」

    android:layout_height=」fill_parent」

    android:orientation=」vertical」 >

    <TextView

        android:layout_width=」fill_parent」

        android:layout_height=」wrap_content」

        android:text=」@string/hello」 />

    <FrameLayout

        android:id=」@+id/ffff」

        android:layout_width=」match_parent」

        android:layout_height=」wrap_content」></FrameLayout>

</LinearLayout>

layout/ffff.xml

<?xml version=」1.0″ encoding=」utf-8″?>

<LinearLayout xmlns:android=」http://schemas.android.com/apk/res/android」

    android:layout_width=」match_parent」

    android:layout_height=」match_parent」

    android:orientation=」vertical」 >

    <CheckBox

        android:id=」@+id/checkBox1″

        android:layout_width=」wrap_content」

        android:layout_height=」wrap_content」

        android:text=」CheckBox」 />

</LinearLayout>

接下來看activity中怎麼寫的

這裏分3中狀況

first, no attachToRoot params

activity 中的部分代碼,注意看紅色部分

        setContentView(R.layout.main);

        ViewGroup v = (ViewGroup) findViewById(R.id.ffff);

        View vv = LayoutInflater.from(this).inflate(R.layout.ffff, v);

 

佈局結構圖

Second, params attachToRoot is false

View vv = LayoutInflater.from(this).inflate(R.layout.ffff, v, false);

發現沒有了ffff.xml 中的內容

經過結構圖查看,確實沒有了

Third,

        ViewGroup v = (ViewGroup) findViewById(R.id.ffff);

        View vv = LayoutInflater.from(this).inflate(R.layout.ffff, v, false);

        v.addView(vv);

運行結果

呵呵,又有了。

因此這個參數的做用就是,是否把選取的視圖加入到root中。false 的意思就是不添加到root中。可能須要咱們手動添加。

附註:例子轉自http://www.189works.com/article-43331-1.html

  • 0

相關文章
相關標籤/搜索