底部导航栏实现页面的切换(五):TabHost

本文介绍了一种使用TabHost和TabWidget实现Android应用中选项卡界面的简单方法。通过XML布局文件定义TabHost和其包含的TabWidget及FrameLayout,并在Java代码中通过填充TabSpec来设置每个选项卡的内容和指示器。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

这种用法已经过时了,

jiantu

TabHost实现选项卡界面有多种方法,这里说最简单的一种

继承ActivityGroup,布局中使用TabHost+TabWidget,调用方法tabHost.setup(getLocalActivityManager())

Demo:http://git.oschina.net/AndroidUI/TabActivity

第一步:xml中适应TabHost+TabWidget

TabHost下面包裹TabWidget+FrameLayout

<?xml version="1.0" encoding="utf-8"?>
<TabHost android:id="@+id/mytabhost"
         xmlns:android="http://schemas.android.com/apk/res/android"
         android:layout_width="fill_parent"
         android:layout_height="fill_parent">

    <RelativeLayout
        android:layout_width="fill_parent"
        android:layout_height="wrap_content">

        <TabWidget
            android:id="@android:id/tabs"
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:background="#A39276"
            android:gravity="bottom"
            android:orientation="horizontal">
        </TabWidget>

        <FrameLayout
            android:id="@android:id/tabcontent"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_above="@android:id/tabs"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true">
        </FrameLayout>
    </RelativeLayout>
</TabHost>

java步骤

填充TabSpec的View

LayoutInflater inflater = LayoutInflater.from(context);
View tab1View = inflater.inflate(R.layout.tab1, null);
View tab2View = inflater.inflate(R.layout.tab2, null);
View tab3View = inflater.inflate(R.layout.tab3, null);

创建TabSpec,并把它加入TabHost

TabHost.TabSpec tab1 = tabHost.newTabSpec("Tab1Tag").setIndicator(tab1View).setContent(new Intent(context, Activity_A.class));
TabHost.TabSpec tab2 = tabHost.newTabSpec("Tab2Tag").setIndicator(tab2View).setContent(new Intent(context, Activity_B.class));
TabHost.TabSpec tab3 = tabHost.newTabSpec("Tab3Tag").setIndicator(tab3View).setContent(new Intent(context, Activity_C.class));

把TabSpec加入TabHost

tabHost.addTab(tab1);
tabHost.addTab(tab2);
tabHost.addTab(tab3);

设置默认显示第一页

tabHost.setCurrentTab(0);

不加监听,也可以切换各activity

tabHost.setOnTabChangedListener(new TabHost.OnTabChangeListener() {
    @Override
    public void onTabChanged(String s) {
        switch (s) {
            case "Tab1Tag":
                Log.d(TAG, "Tab1");
                break;
            case "Tab2Tag":
                Log.d(TAG, "Tab2");
                break;
            case "Tab3Tag":
                Log.d(TAG, "Tab3");
                break;
        }
    }
});
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值