歡迎來到Linux教程網
Linux教程網
Linux教程網
Linux教程網
Linux教程網 >> Linux編程 >> Linux編程 >> Android開發心得:LayoutInflater及inflate方法

Android開發心得:LayoutInflater及inflate方法

日期:2017/3/1 9:37:59   编辑:Linux編程

引言:

Android開發心得筆記,先看一段代碼

public void OnCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

這個是Activity創建時執行的方法,其中最後一句大家應該都見過,這個加載布局的最簡單的方法,但是如果,你需要動態加載布局,那就需要使用其他辦法。

那就是LayoutInfater的inflate方法。

一。獲得 LayoutInflater 實例的三種方式

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

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

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

二。inflate方法

public View inflate(int Resourece,ViewGroup root)

作用:填充一個新的視圖層次結構從指定的XML資源文件中

reSource:View的layout的ID

root: 生成的層次結構的根視圖

return 填充的層次結構的根視圖

如果參數root提供了,那麼root就是根視圖;否則填充的XML文件的根就是根視圖。其余幾個重載的inflate函數類似。

在View類中,也有inflate方法,相關的可以看下這篇文章 http://www.linuxidc.com/Linux/2014-11/108818.htm

結束語:

這段代碼和之前說的那最後一句是一個意思:

LayoutInflater inflate = LayoutInflater.from(this);
View view = inflate.inflate(R.layout.main,null);
setContentView(view);

Android 4.4.4 發布下載 http://www.linuxidc.com/Linux/2014-06/103467.htm

最簡單的Ubuntu Touch & Android 雙系統安裝方式 http://www.linuxidc.com/Linux/2014-01/94881.htm

在Nexus上實現Ubuntu和Android 4.4.2 雙啟動 http://www.linuxidc.com/Linux/2014-05/101849.htm

Ubuntu 14.04 配置 Android SDK 開發環境 http://www.linuxidc.com/Linux/2014-05/101039.htm

64位Ubuntu 11.10下Android開發環境的搭建(JDK+Eclipse+ADT+Android SDK詳細) http://www.linuxidc.com/Linux/2013-06/85303.htm

Ubuntu 14.04 x64配置Android 4.4 kitkat編譯環境的方法 http://www.linuxidc.com/Linux/2014-04/101148.htm

Ubuntu 12.10 x64 安裝 Android SDK http://www.linuxidc.com/Linux/2013-03/82005.htm

更多Android相關信息見Android 專題頁面 http://www.linuxidc.com/topicnews.aspx?tid=11

Copyright © Linux教程網 All Rights Reserved