編輯:關於 Android 程式設計
Android getViewById 與 getLayoutInflater().inflate() 詳解及比較
剛學習 Android 時,常搞不清 getViewById 與 getLayoutInflater().inflate() 該如何區分使用,這裡整理資料供大家參考。
LayoutInflater
要理解這個問題,先得知道什麼是 LayoutInflater。根據官方 API:Instantiates a layout XML file into its corresponding View objects,可知這個類用來根據 xml 布局檔實例化相應的 View。
getLayoutInflater()
API 文檔緊接著寫道:It is never used directly,可知 LayoutInflater 不能直接 new 初始化。同時,對於未被載入或想動態載入的界面,都需要用 LayoutInflater.inflate() 來載入。
既然有用又不能 new,取得實例一般有三種方式:
1. LayoutInflater inflater = getLayoutInflater(); //調用Activity的getLayoutInflater() 2. LayoutInflater localinflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 3. LayoutInflater inflater = LayoutInflater.from(context);
看源碼會發現這三種方式本質相同:
Activity 的 getLayoutInflater() 其實是調用 PhoneWindow 的 getLayoutInflater():
public PhoneWindow(Context context) { super(context); mLayoutInflater = LayoutInflater.from(context); } 而 LayoutInflater.from(context):
public static LayoutInflater from(Context context) { LayoutInflater LayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); if (LayoutInflater == null) { thrownew AssertionError("LayoutInflater not found."); } return LayoutInflater; } 可見它其實調用 context.getSystemService()。
結論:這三種方式最終本質都是調用 Context.getSystemService()。
inflate()
根據 SDK API 文檔:Inflate a new view hierarchy from the specified xml resource,即 inflate() 用來找 xml 布局檔並實例化成 View 對象。
LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.custom, (ViewGroup)findViewById(R.id.test)); EditText editText = (EditText)view.findViewById(R.id.content);
getViewById()
findViewById() 是剛接觸 Android 時最先遇到的方法之一,用來找 xml 布局檔下的具體 widget 控件(如 Button、TextView 等)。
總結一句:對於未被載入或想動態載入的界面,需用 LayoutInflater.inflate();getLayoutInflater() 回傳 LayoutInflater 實例,所以 getLayoutInflater().inflate() 是用來找 res/layout 下的 xml 布局檔並實例化;而 findViewById() 則是找具體布局檔中的具體 widget 控件。希望這份整理能幫助到你。
Android Location 定位實例:取得經緯度並顯示
Location 在 Android 的用途定位常用於取得經緯度,再延伸成天氣、地圖或地區服務。Android 中可透過 LocationManager 取得位置,常見來
紅米Pro多少錢?規格、雙鏡頭與價格預測整理
紅米手機官方微博正式公布了 7 月 27 日新品發佈會的主角之一——紅米Pro。場上還出現了一款神秘新品,從輪廓判斷大概就是傳了很久的小米筆記型電腦。紅米Pro的定位與價
Android PopupWindow 實作:多層級聯動篩選選單
在不少列表頁與搜尋場景裡,我們會看到「一級選單切換、二級選項連動更新」的篩選設計。本文以 PopupWindow 搭配雙 ListView 為基礎,示範如何打造這樣一個層
Android 學習筆記:Home Screen Widgets(二)配置、資料與生命週期
上一篇我們完成了 widget 的定義,也看見它出現在 widget 列表裡。當使用者把 widget 拖曳到主畫面時,如果 appwidget-provider 中定義