最简单的TabHost

创建一个项目。Tab继承自TabActivity.

main.xml:

<?xml version="1.0" encoding="utf-8"?><!--  这里是根节点布局  -->
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             android:orientation="vertical"
             android:layout_width="fill_parent"
             android:layout_height="fill_parent">
    <!-- 第一个Tab 对应的布局  -->
    <TextView
            android:id="@+id/tab1"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:text="tab1"/>
    <!-- 第二个Tab 对应的布局  -->
    <TextView
            android:id="@+id/tab2"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:text="tab2"/>
    <!-- 第三个Tab 对应的布局  -->
    <TextView
            android:id="@+id/tab3"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:text="tab3"/>
</FrameLayout>

 

Tab.class

package com.example.Tab;

import android.app.TabActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.widget.TabHost;
import android.widget.Toast;

public class Tab extends TabActivity
{
    private TabHost tabHost;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        super.onCreate(savedInstanceState);
        //从TabActivity上面获取放置Tab的TabHost
        tabHost = getTabHost();
        //from(this)从这个TabActivity获取LayoutInflater
        //R.layout.main 存放Tab布局
        //通过TabHost获得存放Tab标签页内容的FrameLayout
        //是否将inflate 拴系到根布局元素上
        LayoutInflater.from(this).inflate(R.layout.main, tabHost.getTabContentView(), true);
        //设置TabHost的颜色
        tabHost.setBackgroundColor(Color.argb(150, 150, 150, 150));
        //制造一个新的标签tab1,这个名字就是onTabChanged中的参数s
        //设置一下显示的标题为Tab_1,设置一下标签图标
        //设置一下该标签页的布局内容为R.id.tab1,这是FrameLayout中的一个子Layout
        tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator("Tab_1", getResources().getDrawable(R.drawable.icon))
                .setContent(R.id.tab1));
        tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator("Tab_2", getResources().getDrawable(R.drawable.icon))
                .setContent(R.id.tab2));
        tabHost.addTab(tabHost.newTabSpec("tab3").setIndicator("Tab_3", getResources().getDrawable(R.drawable.icon))
                .setContent(R.id.tab3));
        //设置标签切换动作
        tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener()
        {
            @Override
            public void onTabChanged(String s)
            {
                Toast.makeText(Tab.this, "Tab Change to " + s, Toast.LENGTH_LONG).show();
            }
        });
        setContentView(tabHost);
    }
}

 

 

效果:

 

参考:

http://www.apkbus.com/android-720-1-1.html

http://my.oschina.net/zt1212/blog/82786

posted @ 2013-07-17 15:25  Norcy  阅读(3005)  评论(0编辑  收藏  举报