2013-02-05 33 views
0

我是Android的初學者開發人員:爲什麼我在android中使用layoutinflater?

你能解釋一下layoutinflater的功能嗎?你能解釋一下它的用途嗎?特別是在這段代碼中?

我有這樣的代碼:

private class MyPagerAdapter extends PagerAdapter { 

    public int getCount() { 
     return 5; 
    } 

    public Object instantiateItem(View collection, int position) { 

    *** LayoutInflater inflater = (LayoutInflater) collection.getContext() 
        .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 

     int resId = 0; 
     switch (position) { 
     case 0: 
      resId = R.layout.farleft; 
      break; 
     case 1: 
      resId = R.layout.left; 
      break; 
     case 2: 
      resId = R.layout.middle; 
      break; 
     case 3: 
      resId = R.layout.right; 
      break; 
     case 4: 
      resId = R.layout.farright; 
      break; 
     } 

     View view = inflater.inflate(resId, null); 

     ((ViewPager) collection).addView(view, 0); 

     return view; 
    } 
+1

'解釋爲什麼我一般和空間使用此代碼?'搞笑的是,我們應該解釋一下你爲什麼使用它......還有文檔很短,容易理解。你甚至試過看過嗎? – WarrenFaith

+0

我不寫,我從代碼:mobile.tutsplus.com/tutorials/android/android-user-interface-design-horizo​​ntal-view-paging/。但我不明白爲什麼在代碼中使用layoutinflater。 – MohammadTofi

+0

如果你還沒有寫出來,不要說「爲什麼我用......」。首先提供像你剛剛提到的一些背景應該已經完成​​。 – WarrenFaith

回答

4

的LayoutInflater服務您的XML佈局的存儲的副本轉換成在應用程序的內存空間真正的實例化視圖的集合。

  • 您在編輯器中創建的佈局保存爲XML。
  • XML作爲資源嵌入到您的應用程序中。
  • layoutinflater讀取資源文件。
  • 然後它創建您指定爲對象的視圖。
  • 您現在可以從代碼中操作視圖對象。

Activity類爲你做這個過程中自動神奇,當你調用setContentView(int)

相關問題