Android之setContentView和LayoutInflater


setContentView:

1.常用的構造函數:

  1)setContentView(int layoutResID)

2)setContentView(View view)

3)setContentView(View view, ViewGroup.LayoutParams params)

2.用法

1)setContentView(R.layout.main);

2)LayoutInflater inflater = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);

View view = (View) inflater.inflate(R.layout.apploader, null, true);

setContentView(view);

3.兩種用法的適用場景:

    setContentView()一旦調用, layout就會立刻顯示UI;而inflate只會把Layout形成一個以view類實現成的對象,有需要時再用setContentView(view)顯示出來。

    一般在activity中通過setContentView()將界面顯示出來,但是如果要在非activity中如何對控件布局進行設置操作,就需LayoutInflater動態加載。

 

LayoutInflater:

獲得 LayoutInflater 實例的三種方式

1. LayoutInflater inflater = getLayoutInflater();  //調用Activity的getLayoutInflater()

2. LayoutInflater localinflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

3. LayoutInflater inflater = LayoutInflater.from(context);

其實,這三種方式本質是相同的,從源碼中可以得出結論:這三種方式最終本質是都是調用的Context.getSystemService()

 --------------------------------------------------------------------

PS: 歡迎關注公眾號"Devin說",會不定期更新Java相關技術知識。

--------------------------------------------------------------------

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM