LayoutInflater的inflate函數用法詳解,layoutinflater用法

來源:互聯網
上載者:User

LayoutInflater的inflate函數用法詳解,layoutinflater用法
LayoutInflater的inflate函數用法詳解

LayoutInflater作用是將layout的xml布局檔案執行個體化為View類對象。

擷取LayoutInflater的方法有如下三種:

?
LayoutInflater inflater=(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);View layout = inflater.inflate(R.layout.main, null); LayoutInflater inflater = LayoutInflater.from(context); (該方法實質就是第一種方法,可參考原始碼)View layout = inflater.inflate(R.layout.main, null); LayoutInflater inflater = getLayoutInflater();(在Activity中可以使用,實際上是View子類下window的一個函數)View layout = inflater.inflate(R.layout.main, null);

一直有點糾結setContentView和inflate的區別找了一些資料。寫了個小程式看了下:

?
publicclass MyInflate extendsActivity{    privateTextView tv;    publicvoid OnCreate(Bundle savedInstanceState){        super.onCreate(savedInstanceState);        //setContentView(R.layout.main);        //tv = (TextView) findViewById(R.id.tv);         LayoutInflater inflate = LayoutInflater.from(this);        View view = inflate.inflate(R.layout.main,null);        setContentView(view);    }}

上述注釋掉的代碼和沒有注釋掉的代碼兩種情況是相同的。

區別:
setContentView()一旦調用, layout就會立刻顯示UI;而inflate只會把Layout形成一個以view類實現成的對象,有需要時再用setContentView(view)顯示出來。一般在activity中通過setContentView()將介面顯示出來,但是如果在非activity中如何對控制項布局設定作業了,這就需要LayoutInflater動態載入。

public View inflate(int Resourece,ViewGroup root)
作用:填充一個新的視圖階層從指定的XML資源檔中
reSource:View的layout的ID
root: 產生的階層的根視圖
return 填充的階層的根視圖。如果參數root提供了,那麼root就是根視圖;否則填充的XML檔案的根就是根視圖。

其餘幾個重載的inflate函數類似。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.