android中LayoutInflater以及inflate

來源:互聯網
上載者:User

轉載:http://hi.baidu.com/aspxdiyer/item/5879980402843519eafe388f

一、LayoutInflater

LayoutInflater其實是在res/layout/下找到xml布局檔案,並且將其執行個體化,這個和findViewById()有點相似,後者是找xml布局檔案下的具體widget控制項(如Button、TextView等)

作用:

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

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

LayoutInflater 是一個抽象類別,在文檔中如下聲明:

public abstract class LayoutInflater extends Object   

獲得 LayoutInflater 執行個體的三種方式

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

例:View toastRoot = getLayoutInflater().inflate(R.layout.toast, null);

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

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

例:View convertView = LayoutInflater.from(mContext).inflate(R.layout.activity_contact, null);

二、inflate

通俗的說,inflate就相當於將一個xml中定義的布局找出來.因為在一個Activity裡如果直接用findViewById()的話,對應的是setConentView()的那個layout裡的組件.

因此如果你的Activity裡如果用到別的layout,比如對話方塊上的layout,你還要設定對話方塊上的layout裡的組件(像圖片ImageView,文字TextView)上的內容,你就必須用inflate()先將對話方塊上的layout找出來,然後再用這個layout對象去找到它上面的組件,如:

  

  View view=View.inflate(this,R.layout.dialog_layout,null);

       TextView dialogTV=(TextView)view.findViewById(R.id.dialog_tv);

  

  dialogTV.setText("abcd");

  

  如果組件R.id.dialog_tv是對話方塊上的組件,而你直接用this.findViewById(R.id.dialog_tv)肯定會報錯.

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.