TabHost使用小结

使用TabHost 可以在一个屏幕间进行不同版面的切换,例如android自带的拨号应用。
完成一个TabHost的步骤:
一、设计布局文件,Tabhost布局文件一般使用FrameLayout,在FrameLayout中添加每个Tab页面的视图,但必须要有id,例如:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent">

<!-- 第一个Tab 对应的布局 -->
<!-- Tab内容必须用Layout布局将view包含,否则在程序中找不到View -->
<LinearLayout android:id="@+id/tab01"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:orientation="vertical">
<ListView android:id="@+id/weather" android:layout_width="fill_parent"
android:layout_height="fill_parent">
</ListView>
</LinearLayout>

<!-- 第二个Tab 对应的布局 -->
<LinearLayout android:id="@+id/tab02"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:orientation="vertical">
<TextView android:id="@+id/weath_detail"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:text="tab">
</TextView>
</LinearLayout>

<!-- 第三个Tab 对应的布局 -->
<LinearLayout android:id="@+id/tab03"
android:layout_width="fill_parent" android:layout_height="fill_parent"
android:orientation="vertical">
<TextView android:id="@+id/city_detail" android:layout_width="fill_parent"
android:layout_height="fill_parent" android:text="tab">
</TextView>
</LinearLayout>
</FrameLayout>

[color=red]注意:每个Tab页面都要有自己的layout,负责在代码中通过Id无法找到相对应的视图[/color]
二、创建展示TabHost的Activity。
1、我们可以直接继承TabActivity,再通过getTabHost()方法得到TabHost对象。例如:
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
myTabHost = this.getTabHost();
//绑定布局文件
LayoutInflater.from(this).inflate(R.layout.tab_host,
myTabHost.getTabContentView(),
true);

initTabHost();
setTitle(weather.getCityName());
//设定显示内容
setContentView(myTabHost);
}

2,为TabHost添加要显示的tab,一个tab就是相应的一个选项卡。例如:
//添加tab
myTabHost.addTab(myTabHost.newTabSpec(TAB_1) //tab的Tag
.setIndicator("城市天气") //tab的标题
.setContent(R.id.tab01)); //tab的显示内容
myTabHost.addTab(myTabHost.newTabSpec(TAB_2)
.setIndicator("天气详情")
.setContent(R.id.tab02));
myTabHost.addTab(myTabHost.newTabSpec(TAB_3)
.setIndicator("城市介绍")
.setContent(R.id.tab03));
3,为Tabhost添加选项卡改变监听,在选项卡改变时做相应处理。例如:
//添加OnTabChangedListener监听,此监听为选项卡改变监听
myTabHost.setOnTabChangedListener(this);
监听处理方法
public void onTabChanged(String tabId)
{
if (tabId.equals(TAB_1))
{
//初始化标签1
initTab1();
}
else if (tabId.equals(TAB_2))
{
//初始化标签2
initTab2();
}
else if (tabId.equals(TAB_3))
{
//初始化标签3
initTab3();
}

}

4,修改Tab显示内容
private void initTab2()
{
//得到tab内容的视图
TextView weathDetailText = (TextView)findViewById(R.id.weath_detail);
weathDetailText.setText(weather.getLiveWeather());
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值