Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android getViewById 與 getLayoutInflater().inflate() 詳解及比較

編輯:關於 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 控件。希望這份整理能幫助到你。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved