先来一张图展示一下Tab。
在创建Tab之前,先把Tab的结构搞清楚。它的结构是这样的:
最外层是一个Tabhost,Tabhost里装了些选项卡(TabSpec),每个选项卡有自己的指示符(Indicator,就是顶部可点的那个区块)和内容(Content,下半部分展示内容的区块)。
现在,要做的事情就很清楚了:
1、创建Tabhost
2、创建TabSpec并给TabSpec赋值
3、把TabSpec添加到Tabhost中
那问题又接着来了。
1、如何创建Tabhost?
Android为我们提供了TabActivity,我们只要继承它,就可以得到Tabhost了。看代码:
public class HomeActivity extends TabActivity { @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); //获取Tabhost TabHost tabhost = this.getTabHost(); }
2、如何创建TabSpec,如何赋值?
我们得到tabhost之后,通过它我们就可以创建新的选项卡,看代码:
// 选项卡的内容先在main文件中写好,当然你不用非得写在main里的。xml文件内容具体在后面给出。 // 这里相当于把Tab要用到的布局与Tabhost绑定起来。 LayoutInflater.from(this).inflate(R.layout.main, tabhost.getTabContentView() ,true); // 此处tab1相当于是选项卡的名字 TabSpec tabSpec1 = tabhost.newTabSpec("tab1"); TabSpec tabSpec2 = tabhost.newTabSpec("tab2"); TabSpec tabSpec3 = tabhost.newTabSpec("tab3"); // 设置选项卡头部的信息,也可以给他设置图片,只需要用setIndicator的重载方法即可 tabSpec1.setIndicator("首页"); tabSpec2.setIndicator("吼吼"); tabSpec3.setIndicator("私信"); // 设置选项卡的内容,共有三种方法,以下是api中的原文 // 1) the id of a View // 2) a TabHost.TabContentFactory that creates the View content. // 3) an Intent that launches an Activity // 此处用的是第一种方法,即先在xml中布局好再到这里来设置。 tabSpec1.setContent(R.id.tab1); tabSpec2.setContent(R.id.tab2); tabSpec3.setContent(R.id.tab3);
3、如何添加?
这最非常容易了,看代码:
tabhost.addTab(tabSpec1); tabhost.addTab(tabSpec2); tabhost.addTab(tabSpec3);
最后还要加上一句
setContentView(tabhost);
这就差不多了。
来看看main.xml里的内容。注意每个LinearLayout通过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"
>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tab1"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tab2"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/tab3"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:id="@+id/username"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>
</FrameLayout>