Android——inflate 將一個xml中定義的布局找出來

來源:互聯網
上載者:User

標籤:

通俗的說,inflate就相當於將一個xml中定義的布局找出來.
  
  因為在一個Activity裡如果直接用findViewById()的話,對應的是setConentView()的那個layout裡的組件.
  
  因此如果你的Activity裡如果用到別的layout,比如對話方塊上的layout,你還要設定對話方塊上的layout裡的組件(像圖片ImageView,文字TextView)上的內容,你就必須用inflate()先將對話方塊上的layout找出來,然後再用這個layout對象去找到它上面的組件,如:
  
  Viewview=View.inflate(this,R.layout.dialog_layout,null);
  
  TextViewdialogTV=(TextView)view.findViewById(R.id.dialog_tv);
  
  dialogTV.setText("abcd");
  
  如果組件R.id.dialog_tv是對話方塊上的組件,而你直接用this.findViewById(R.id.dialog_tv)肯定會報錯.
  
  三種方式可以產生LayoutInflater:
  
  LayoutInflaterinflater=LayoutInflater.from(this);
  
  LayoutInflaterinflater=getLayoutInflater();
  
  LayoutInflaterinflater=(LayoutInflater)this.getSystemService(LAYOUT_INFLATER_SERVICE);
  
  然後調用inflate方法將xml布局檔案轉成View

  LayoutInflater layoutInflater = LayoutInflater.from(DialogActivity.this);
                        // 得到自訂對話方塊
      final View dialogView = layoutInflater.inflate(R.layout.dialog_login, null);


  
  publicViewinflate(intresource,ViewGrouproot,booleanattachToRoot)
  
  在View類中,也有inflate方法
  
  publicstaticViewinflate(Contextcontext,intresource,ViewGrouproot)

 

 

引自:http://android.tgbus.com/Android/tutorial/201104/348009.shtml

Android——inflate 將一個xml中定義的布局找出來

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.