您的位置:首页 > 其它

TabHost简单使用示例

2015-10-19 18:20 295 查看

1.综述

在Android的开发中,经常需要实现页面Tab的功能,比较简答的一种方式就是使用TabHost实现。顾名思义,TabHost即是包含若干个Tab的一个Tab容器。那么,当我们要使用TabHost实现一个界面功能的时候,我们是如何开始的呢?

2.实现步骤

1)首先写布局文件

布局文件的填写较为简单,如下:
<TabHost
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/tabhost"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">

<TabWidget
android:id="@android:id/tabs"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
</TabWidget>

<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_weight="1">

<LinearLayout
android:id="@+id/page1"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="tab1"/>
</LinearLayout>

<LinearLayout
android:id="@+id/page2"
android:layout_width="fill_parent"
android:layout_height="fill_parent">

<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:gravity="center"
android:text="tab2"/>
</LinearLayout>

</FrameLayout>
</LinearLayout>

</TabHost>
使用中,需要注意的点是:
TabHost的id需要设为
<span style="white-space:pre">	</span>android:id="@android:id/tabhost"
TabWidget为tab键下方的状态地址栏,其id需设置为<pre name="code" class="html"><span style="white-space:pre">	</span>android:id="@android:id/tabs"
FrameLayout为TabHost的待填充内容,其id需设置为
<pre name="code" class="html" style="font-size: 12px;"><span style="white-space:pre">	</span>android:id="@android:id/tabcontent"
并且权重需要设置为

<pre name="code" class="html" style="font-size: 13.3333339691162px;"><span style="white-space:pre">	</span>android:layout_weight="1"
如此,一个简单的TabHost就设置完成了。

2)Java源码

源码如下:
package com.gtja.com.tabfragment;

import android.app.TabActivity;
import android.os.Bundle;
import android.widget.TabHost;

public class MainActivity extends TabActivity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);

TabHost tabHost = getTabHost();
TabHost.TabSpec page1 = tabHost.newTabSpec("tab1")
.setIndicator("tab1")
.setContent(R.id.page1);
tabHost.addTab(page1);

TabHost.TabSpec page2 = tabHost.newTabSpec("tab2")
.setIndicator("tab2")
.setContent(R.id.page2);
tabHost.addTab(page2);

}

}
在源码中,getTabHost()获取TabHost对象,setIndicator()设置对应tab的提示,addTab()则是将该TabSpec添加到TabHost中。

3)实现效果

实现效果如下:





至此,一个基本的TabHost的页面跳转实现了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: