這篇文章給大家介紹inflater 如何在Android中使用,內(nèi)容非常詳細(xì),感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。
網(wǎng)站建設(shè)哪家好,找成都創(chuàng)新互聯(lián)!專注于網(wǎng)頁設(shè)計、網(wǎng)站建設(shè)、微信開發(fā)、微信平臺小程序開發(fā)、集團企業(yè)網(wǎng)站建設(shè)等服務(wù)項目。為回饋新老客戶創(chuàng)新互聯(lián)還提供了濟源免費建站歡迎大家使用!
1、對于一個沒有被載入或者想要動態(tài)載入的界面,都需要使用LayoutInflater.inflate()來載入;
2、對于一個已經(jīng)載入的界面,就可以使用Activiyt.findViewById()方法來獲得其中的界面元素。
文檔中的聲明:
public abstract class LayoutInflater extends Object
三種實例化方式:
1.LayoutInflater inflater = getLayoutInflater(); //調(diào)用Activity的getLayoutInflater()
2.LayoutInflater localinflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
3. LayoutInflater inflater = LayoutInflater.from(context);
其實,這三種方式本質(zhì)是相同的,從源碼中可以看出:
getLayoutInflater():
Activity 的 getLayoutInflater() 方法是調(diào)用 PhoneWindow 的getLayoutInflater()方法,看一下該源代碼:
public PhoneWindow(Context context) { super(context); mLayoutInflater = LayoutInflater.from(context); }
可以看出它其實是調(diào)用 LayoutInflater.from(context)。
LayoutInflater.from(context):
public static LayoutInflater from(Context context) { LayoutInflater LayoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE); if (LayoutInflater == null) { throw new AssertionError("LayoutInflater not found."); } return LayoutInflater; }
可以看出它其實調(diào)用 context.getSystemService()。
結(jié)論:所以這三種方式最終本質(zhì)是都是調(diào)用的Context.getSystemService()。
inflate 方法
通過 sdk 的 api 文檔,可以知道該方法有以下幾種過載形式,返回值均是 View 對象,如下
public View inflate (int resource, ViewGroup root) public View inflate (XmlPullParser parser, ViewGroup root) public View inflate (XmlPullParser parser, ViewGroup root, boolean attachToRoot) public View inflate (int resource, ViewGroup root, boolean attachToRoot)
示意代碼:
LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE); View view = inflater.inflate(R.layout.custom, (ViewGroup)findViewById(R.id.test)); //EditText editText = (EditText)findViewById(R.id.content);// error EditText editText = (EditText)view.findViewById(R.id.content); **對于上面代碼,指定了第二個參數(shù) ViewGroup root,當(dāng)然你也可以設(shè)置為 null 值。**
注意:
·inflate 方法與 findViewById 方法不同;
·inflater 是用來找 res/layout 下的 xml 布局文件,并且實例化;
·findViewById() 是找具體 xml 布局文件中的具體 widget 控件(如:Button、TextView 等)。
關(guān)于inflater 如何在Android中使用就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。
本文標(biāo)題:inflater如何在Android中使用
網(wǎng)站URL:http://sd-ha.com/article8/gegsip.html
成都網(wǎng)站建設(shè)公司_創(chuàng)新互聯(lián),為您提供網(wǎng)站內(nèi)鏈、靜態(tài)網(wǎng)站、手機網(wǎng)站建設(shè)、企業(yè)建站、網(wǎng)站收錄、網(wǎng)站設(shè)計
聲明:本網(wǎng)站發(fā)布的內(nèi)容(圖片、視頻和文字)以用戶投稿、用戶轉(zhuǎn)載內(nèi)容為主,如果涉及侵權(quán)請盡快告知,我們將會在第一時間刪除。文章觀點不代表本網(wǎng)站立場,如需處理請聯(lián)系客服。電話:028-86922220;郵箱:631063699@qq.com。內(nèi)容未經(jīng)允許不得轉(zhuǎn)載,或轉(zhuǎn)載時需注明來源: 創(chuàng)新互聯(lián)