1.xml布局文件
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<!-- 此处使用帧布局 -->
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:id="@+id/tab1"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="我是Tab1"/>
</LinearLayout>
<LinearLayout
android:id="@+id/tab2"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="我是Tab2"/>
</LinearLayout>
<LinearLayout
android:id="@+id/tab3"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="我是Tab3"/>
</LinearLayout>
<LinearLayout
android:id="@+id/tab4"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="我是Tab4"/>
</LinearLayout>
</FrameLayout>
</LinearLayout>
2.Java部分
// 方便编写直接继承TabActivity
public class MainActivity extends TabActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
TabHost tabHost=getTabHost(); //获得tabhost容器对象
LayoutInflater.from(this).inflate(R.layout.activity_main, tabHost.getTabContentView(), true); //动态加载布局文件到tabhost容器中TabConetentView中
TabSpec spec; //声明标签页对象
spec = tabHost.newTabSpec("tab1"); //tag标签
spec.setIndicator("TAB1"); //显示的标签
spec.setContent(R.id.tab1); //绑定页视图
tabHost.addTab(spec); //添加到容器
spec = tabHost.newTabSpec("tab2");
spec.setIndicator("TAB2");
spec.setContent(R.id.tab2);
tabHost.addTab(spec);
spec = tabHost.newTabSpec("tab3");
spec.setIndicator("TAB3");
spec.setContent(R.id.tab3);
tabHost.addTab(spec);
spec = tabHost.newTabSpec("tab4");
spec.setIndicator("TAB4");
spec.setContent(R.id.tab4);
tabHost.addTab(spec);
tabHost.setCurrentTab(0); //默认显示的页
}
}
3.添加Tab页改变事件,实现(implements) TabHost.OnTabChangeListener接口将自动重写onTabChanged方法
tabHost.setOnTabChangedListener(this); //设置监听
@Override //事件写于此
public void onTabChanged(String tabId) {
// TODO Auto-generated method stub
Log.e(TAG, tabId);
}
4.实现TabHost.TabContentFactory接口对Tab页进行创建指定的View,将自动重写createTabContent方法。
@Override
public View createTabContent(final String tag) {
// TODO Auto-generated method stub
View view = null;
view = LayoutInflater.from(this).inflate(R.layout.list, null);
if ("tab1".equals(tag)) {
// 用到tag标签对象,用于判断是哪个Tab页,tag标签可定义为常理
//此处写当前页中需要处理的语句
}
return view;
}
R.layout.list就是要绑定的布局视图。