Android中的选项卡是一个非常方便的分类组件。例如,你可以把通话记录使用的选项卡(Tab)来分类,将所有通话记录、已接来电、未接来电等分类显示。下面的实例就是使用Tab来完成这个功能的。
使用Tab组件的步骤说明如下:
1、在布局文件中使用FrameLayout列出Tab组件及Tab中的内容组件 2、Activity要继承TabActivity 3、调用TabActivity的getTabHost()方法获得TabHost对象 4、通过TabHost创建Tab选项
布局代码:
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:id="@+id/FrameLayout1" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <TabHost android:id="@android:id/tabhost" android:layout_width="match_parent" android:layout_height="match_parent" /> <TextView android:id="@+id/TextView01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="所有通话记录" /> <TextView android:id="@+id/TextView02" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="已接来电" /> <TextView android:id="@+id/TextView03" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="未接来电" /> </FrameLayout>
Activity代码:
package com.example.android_ui_tab;
import android.os.Bundle; import android.app.TabActivity; import android.view.LayoutInflater; import android.view.Menu; import android.widget.TabHost;
public class MainActivity extends TabActivity {
@Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); // 获得TabHost TabHost th = getTabHost(); LayoutInflater.from(this).inflate(R.layout.activity_main, th.getTabContentView(), true); // 设置Tab的标签内容和显示内容 th.addTab(th.newTabSpec("all").setIndicator("所有通话记录").setContent(R.id.TextView01)); th.addTab(th.newTabSpec("ok").setIndicator("已接来电").setContent(R.id.TextView02)); th.addTab(th.newTabSpec("cancel").setIndicator("未接来电").setContent(R.id.TextView03)); }
@Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; }
}
运行效果如下图: