標籤:使用 layout inf at t e 作用 layoutinflater out
作用:用來執行個體化一個XML檔案到指定View中。與findViewById類似,不同的是LayoutInflater找的res檔案下的沒有被載入或需動態被載入,對於已經載入的Activity可以使用findViewById來獲得其中的介面元素。
獲得LayoutInflater的幾種方式:
1. LayoutInflater inflater = getLayoutInflater();//調用Activity的getLayoutInflater() Returns LayoutInflater The shared LayoutInflater.2. LayoutInflater inflater = LayoutInflater.from(context); //Obtains the LayoutInflater from the given context.3. LayoutInflater inflater = (LayoutInflater)context.getSystemService (Context.LAYOUT_INFLATER_SERVICE);//A LayoutInflater for inflating layout resources in this context
從源碼得到三種都是調用Context.getSystemService(),它根據NAME來取得對應的Object然後轉換成相應服務物件。http://developer.android.com/reference/android/content/Context.html#getSystemService(java.lang.String) LAYOUT_INFLATER_SERVICELayoutInflater取得xml裡定義的view。
返回View:使用inflater方法。
View view = inflater.inflate(R.layout.newview, null); setContentView(view);//顯示
來自為知筆記(Wiz)
LayoutInflater作用及使用