在學Layout這部分時看到了這段程式碼
LinearLayout linear_layout = (LinearLayout)getLayoutInflater().inflate(R.layout.layout_to_be_inflate,null);
功能是把layout_to_be_inflate這個xml檔生成一個linearlayout物件
當中出現了 LayoutInflater這不知道意義何在的東西
所以就找了一下
Google是這麼講的 :
「Instantiates a layout XML file into its corresponding View objects. It is never used directly. Instead, usegetLayoutInflater() or getSystemService(String) to retrieve a standard LayoutInflater instance that is already hooked up to the current context and correctly configured for the device you are running on.」
根據上述Google提供的說明再加上個人腦補
LayoutInflater 主要的用途是 將XML檔動態載入
且LayoutInflater不應該直接出現(應該是指LayoutInflater 變數名= new LayoutInflater();),而是透過Activity的getLayoutInflater()方法或getSystemService(Layout_inflater_service)方法來取得
而要獲得一個LayoutInflater物件
有兩個方法可用
第一種
LayoutInflater li = LayoutInflater.from(this);
這樣 LayoutInflater型態的 li 變數就指到了現在使用中的layout的layoutinflater
from(context)是LayoutInflater類別的靜態方法,會回傳傳入的context的layoutinflater
Activity是context的子類別
沒有留言:
張貼留言