日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 运维知识 > Android >内容正文

Android

Android inflate方法与 findViewById 方法区别

發布時間:2024/4/15 Android 39 豆豆
生活随笔 收集整理的這篇文章主要介紹了 Android inflate方法与 findViewById 方法区别 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

在實際開發中LayoutInflater這個類還是非常有用的,它的作用類似于findViewById()。不同點是LayoutInflater是用來找res/layout/下的xml布局文件,并且實例化;而findViewById()是找xml布局文件下的具體widget控件(如Button、TextView等)。

具體作用:

1、對于一個沒有被載入或者想要動態載入的界面,都需要使用LayoutInflater.inflate()來載入;

2、對于一個已經載入的界面,就可以使用Activiyt.findViewById()方法來獲得其中的界面元素。

?

LayoutInflater作用是將layoutxml布局文件實例化為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);

?

注意:

·inflate方法與 findViewById 方法不同;

·inflater 是用來找 res/layout下的 xml 布局文件,并且實例化;

·findViewById() 是找具體 xml 布局文件中的具體 widget 控件(如:Button、TextView 等)。

?

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

setContentViewinflate的區別

一直有點糾結setContentViewinflate的區別找了一些資料。寫了個小程序看了下:

public class MyInflate extends Activity{private TextView tv;public void 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
ViewlayoutID
root
?生成的層次結構的根視圖
return?
填充的層次結構的根視圖。如果參數root提供了,那么root就是根視圖;否則填充的XML文件的根就是根視圖。

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

?

參考:

1.  http://www.open-open.com/lib/view/open1328837587484.html

2.  http://www.cnblogs.com/shitianzeng/articles/2323427.html


轉自:http://www.cnblogs.com/loyea/archive/2013/04/27/3047248.html

總結

以上是生活随笔為你收集整理的Android inflate方法与 findViewById 方法区别的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。