Android ApiDemos示例解析(193):Views->Tabs->Content By Id

本文介绍了Android中TabActivity及TabHost的使用方法,通过TabHost.TabSpec为Tab窗口添加页面,并展示了如何设置Tab的内容与指示器。示例代码演示了如何通过View资源ID设置Tab内容。

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

本例介绍TabActivity ,在Android新版本不建议使用TabActivity,而是使用Fragment。 TabActivity 提供了分页控件(Tab Control),关键的一个类为TabHost,TabHost 为TabActivity的View,可以通过getTabHost()取得TabActivity 对应的TabHost.

TabHost 可以通过TabHost.TabSpec 来为Tab 窗口添加一个页面,TabSpec 用来描述一个页面(Tab) ,每个Tab 可以有个tag 用来区分Tab窗口的某个页面,indicator (页标题,可以使用文字,图标等来显示) 和Content(页面内容)。

其中Content  使用View资源Id或是TabHost.TabContentFactory构造或是某个Intent实例(该Intent可以启动某个Activity)。这也是为什么TabActivity 为一ActivityGroup 的原因。

本例对应的代码为Tab1.java 采用View资源ID的方法来设置Tab的Content:

TabHost tabHost = getTabHost();

LayoutInflater.from(this).inflate(R.layout.tabs1,
 tabHost.getTabContentView(), true);

tabHost.addTab(tabHost.newTabSpec("tab1")
 .setIndicator("tab1")
 .setContent(R.id.view1));
tabHost.addTab(tabHost.newTabSpec("tab3")
 .setIndicator("tab2")
 .setContent(R.id.view2));
tabHost.addTab(tabHost.newTabSpec("tab3")
 .setIndicator("tab3")
 .setContent(R.id.view3));

要注意的是使用setContent中指定的View,之前需要将它们展开到tabHost.getTabContentView()中。

R.layout.tabs1.xml 定义如下:

<FrameLayout xmlns:android=”http://schemas.android.com/apk/res/android”
android:layout_width=”match_parent”
android:layout_height=”match_parent”>

<TextView android:id=”@+id/view1″
android:background=”@drawable/blue”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:text=”@string/tabs_1_tab_1″/>

<TextView android:id=”@+id/view2″
android:background=”@drawable/red”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:text=”@string/tabs_1_tab_2″/>

<TextView android:id=”@+id/view3″
android:background=”@drawable/green”
android:layout_width=”match_parent”
android:layout_height=”match_parent”
android:text=”@string/tabs_1_tab_3″/>

</FrameLayout>

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值