LayoutInflater詳解以及三種實現方法

2021-07-11 22:25:59 字數 2256 閱讀 1757

在實際開發中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是用來找res layout 下的xml布局檔案,並且例項化 而findviewbyid 是找xml布局檔案下的具體widget控制項 如button textv...

獲取LayoutInflater例項

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

LayoutInflater和inflate的用法

layoutinflater這個類的作用類似於findviewbyid 不同點 layoutinflater是用來找layout下xml布局檔案的,而且它會例項化 findviewbyid 是找具體xml布局檔案下的具體widget控制項,比如 button按鈕 inflate就相當於將乙個xml中...