Android成長之路-LayoutInflater和inflate的用法

來源:互聯網
上載者:User

在這裡用Tabhost的例子來說明:

package cn.csdn.activity;import android.app.TabActivity;import android.os.Bundle;import android.view.LayoutInflater;import android.widget.TabHost;public class TabHostActivity extends TabActivity {@Overrideprotected void onCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);TabHost tabhost = this.getTabHost();/** * LayoutInflater這個類的作用類似於findViewById(), * 不同點: *     LayoutInflater是用來找layout下xml布局檔案的,而且它會執行個體化 *     findViewById()是找具體xml布局檔案下的具體widget控制項,比如:Button按鈕 *  *  *  * inflate就相當於將一個xml中定義的布局找出來.     * 因為如果在一個Activity檔案裡直接用findViewById()這個方法的話, * 那麼它所對應的是setConentView()中調用的那個layout裡的組件.    * 因此如果在同樣的Activity裡用到別的layout的話, *     而且你還要設定這個layout裡的組件(比如:ImageView,TextView)上的內容, *     那麼你就必須用inflate()先將這個layout找出來, 然後再用這個layout對象去找到它上面的組件 *     然後進行一系列的操作 *      *     inflate()方法中參數: *       1.想要用的布局檔案的id *       2.持有選項卡的內容,擷取FrameLayout *       3.true:將此處解析的xml檔案做為根視圖View */LayoutInflater.from(this).inflate(R.layout.tabhost_layout,tabhost.getTabContentView(), true);/**在這裡添加的時候: *       1.必須指定 tab 的內容,必須為 id, 即:setContent(R.id.text) *       2.必須設定tab 上的文字或圖片  , 即:setIndicator("已接電話") *       3.返回一個 TabHost.TabSpec 對象,其參數用於標識一個 tab 的 tag,即:newTabSpec("tab1")*/tabhost.addTab(tabhost.newTabSpec("tab1").setIndicator("已接電話").setContent(R.id.text));tabhost.addTab(tabhost.newTabSpec("tab2").setIndicator("呼出電話",getResources().getDrawable(R.drawable.ic_launcher)).setContent(R.id.text));tabhost.addTab(tabhost.newTabSpec("tab3").setIndicator("未接電話").setContent(R.id.text));}}

 

相關文章

聯繫我們

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