2014-01-30 81 views
2

我在這裏看到很多答案,但我實際上不明白它是什麼以及它爲什麼被使用。什麼時候在Android中使用LayoutInflater

有人可以給一點簡單的描述來理解它嗎? 非常感謝

+4

從文檔「_Instantiates佈局XML文件到其相應的視圖對象._」非常簡單。它將XML轉化爲代碼中的視圖。 – csmckelvey

回答

7

基本上需要在運行時基於XML文件創建(或填充)視圖。例如,如果您需要爲您的ListView項目動態生成視圖,這就是它的全部。

5

LayoutInflater用於使用預定義的XML佈局來操縱Android屏幕。 該類用於將佈局XML文件實例化爲其相應的View對象。 它從不直接使用。相反,使用getLayoutInflater()或getSystemService(String)來檢索已連接到當前上下文的標準LayoutInflater實例。

簡單的程序,用於LayoutInflater- 使這個佈局,您activity_main.xml-

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:id="@+id/main_layout" 
    android:orientation="vertical" 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" > 
    </LinearLayout> 

this is the hidden layout which we will add dynamically,save it as hidden_layout.xml 


<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
       android:id="@+id/hidden_layout" 
       android:layout_width="fill_parent" 
       android:layout_height="fill_parent" 
       android:orientation="vertical"> 

    <TextView android:id="@+id/text_view" 
       android:layout_width="fill_parent" 
       android:layout_height="wrap_content" 
       android:text="Hello, this is the inflated text of hidden layout"/> 

    <EditText android:id="@+id/edit_text" 
       android:layout_width="fill_parent" 
       android:layout_height="wrap_content" 
       android:text="Hello, this is your name"/> 
</LineraLayout> 

現在,這是主要的活動 - 代碼

public class MainActivity extends Activity 
{ 
public void onCreate(Bundle savedInstanceState) 
{ 
super.onCreate(savedInstanceState); 
setContentView(R.layout.activity_main); 

LinearLayout main = (LinearLayout)findViewById(R.id.main_layout); 
     View view = getLayoutInflater().inflate(R.layout.hidden_layout, main,false); 
     main.addView(view); 

} 
} 

音符我們使用「假」屬性,因爲通過這種方式,我們對加載的視圖進行的任何進一步的佈局更改都將生效。如果我們將它設置爲「true」,它將再次返回根對象,這將阻止對加載的對象進行進一步的佈局更改。

相關問題