Android getViewById和getLayoutInflater().inflate()的詳解及比較_Android

來源:互聯網
上載者:User

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

               由於本人剛剛學習Android 對於getViewById和getLayoutInflater().inflate()的方法該如何使用不知如何分別,這裡就上網查下資料整理下,大家可以看下。

LayoutInflater

要明白這個問題首先要知道什麼是LayoutInflater。根據Android的官方API解釋:

Instantiates a layout XML file into its corresponding View objects.

由此可知,這個類是用來根據xml布局檔案來執行個體化相應的View的。

getLayoutInflater()

根據API的文檔解釋,定義後面緊接著一句:

It is never used directly.

由此可知,LayoutInflater不能直接使用,即不能使用new來初始化。同時根據定義可以看出在實際開發中LayoutInflater這個類還是非常有用的,比如對於一個沒有被載入或者想要動態載入的介面,都需要使用LayoutInflater.inflate() 來載入。

既然很有用,又不能直接初始化,肯定會有其他的方式獲得LayoutInflater的執行個體。一般獲得 LayoutInflater 有執行個體的三種方式:

 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)。

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()

inflate 方法 通過 sdk 的 API文檔可知:

Inflate a new view hierarchy from the specified xml resource.

即inflater() 是用來找 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()

getViewById()應該熟悉的,剛接觸android時最先接觸到的幾個方法裡肯定有他。findViewById()是找xml布局檔案下的具體widget控制項(如Button、TextView等)。

最後說一句,對於一個沒有被載入或者想要動態載入的介面,都需要使用LayoutInflater.inflate(),getLayoutInflater()返回LayoutInflater執行個體,所以,可以說getLayoutInflater().inflater() 是用來找 res/layout下的 xml 布局檔案,並且執行個體化;findViewById() 是找具體 xml 布局檔案中的具體 widget 控制項(如:Button、TextView 等)。

感謝閱讀,希望能協助到大家,謝謝大家對本站的支援!

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.