LayoutInflater的獲取與使用

2022-05-13 14:00:12 字數 2287 閱讀 5322

在實際開發中layoutinflater這個類還是非常有用的,它的作用類似於findviewbyid()。不同點是layoutinflater是用來找res/layout/下的xml布局檔案,並且例項化;而findviewbyid()是找xml布局檔案下的具體widget控制項(如button、textview等)。

具體作用:

1、對於乙個沒有被載入或者想要動態載入的介面,都需要使用layoutinflater.inflate()來載入;

2、對於乙個已經載入的介面,就可以使用activiyt.findviewbyid()方法來獲得其中的介面元素。

layoutinflater 是乙個抽象類,在文件中如下宣告:

public

abstract

class

layoutinflater 

extends

object  

獲得 layoutinflater 例項的三種方式

layoutinflater inflater = getlayoutinflater();  //

呼叫activity的getlayoutinflater()

layoutinflater localinflater =(layoutinflater)context.getsystemservice(context.layout_inflater_service);

layoutinflater inflater = layoutinflater.from(context);

其實,這三種方式本質是相同的,從原始碼中可以看出:

getlayoutinflater():

activity 的 getlayoutinflater() 方法是呼叫 phonewindow 的getlayoutinflater()方法,看一下該源**:

1

public

phonewindow(context context)

可以看出它其實是呼叫 layoutinflater.from(context)。

layoutinflater.from(context):

可以看出它其實呼叫 context.getsystemservice()。

結論:所以這三種方式最終本質是都是呼叫的context.getsystemservice()。

inflate 方法

通過 sdk 的 api 文件,可以知道該方法有以下幾種過載形式,返回值均是 view 物件,如下:

1

public view inflate (int

resource, viewgroup root) 23

public

view inflate (xmlpullparser parser, viewgroup root) 45

public view inflate (xmlpullparser parser, viewgroup root, boolean

attachtoroot) 67

public view inflate (int resource, viewgroup root, boolean attachtoroot)

示意**:

1 layoutinflater inflater =(layoutinflater)getsystemservice(layout_inflater_service);  

2 view view =inflater.inflate(r.layout.custom, (viewgroup)findviewbyid(r.id.test)); 34

//edittext edittext = (edittext)findviewbyid(r.id.content);

//error

56 edittext edittext = (edittext)view.findviewbyid(r.id.content);

對於上面**,指定了第二個引數 viewgroup root,當然你也可以設定為 null 值。

注意:·inflate 方法與 findviewbyid 方法不同;

·inflater 是用來找 res/layout 下的 xml 布局檔案,並且例項化;

·findviewbyid() 是找具體 xml 布局檔案中的具體 widget 控制項(如:button、textview 等)。

** 

關於LayoutInflater的用法

參考 在實際開發中,layoutinflater是非常有用的,類似於findviewbyid,不同的是,layoutinflater是用來查詢layout資料夾下的.xml布局檔案的,並且例項化。而findviewbyid是查詢xml下的具體widget控制項。用法 private linearla...

使用LayoutInflater的理解

今天封裝xml布局到view的時候遇到了內容直接變成包裹內容,顯示與寫的布局不符合的情況,檢查後發現是layoutinflater使用錯誤的問題,因此這裡今天就記錄一下layoutinflater的部分理解。layoutinflater是用來找res layout 下的xml布局檔案,並且例項化 類...

常見的LayoutInflater類

抽象類layoutinflater,其作用類似於findviewbyid 方法。不過它是用來找res layout下的xml布局檔案,並且例項化 而findviewbyid 方法僅僅是通過控制項id查詢某xml布局檔案下具體widget控制項 如button textview等 兩者具體用途 1.對...