TabHost控件虽然在高版本的SDK中已经过时,但还是有他的优点的,在很多项目中还可以用到,以下就总结一下
布局文件: main.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"
tools:context=".MainActivity" >
<TabHost
android:id="@android:id/tabhost"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TabWidget
android:id="@android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</TabWidget>
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent" >
</FrameLayout>
</LinearLayout>
</TabHost>
</LinearLayout>
java文件:
package com.succ7.smartsms;
import android.app.TabActivity;
import android.content.Intent;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
@SuppressWarnings("deprecation")
public class MainActivity1 extends TabActivity {
private TabHost tabhost;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//初始化
init();
}
//初始化方法
private void init() {
//找到tabhost控件
tabhost = (TabHost) findViewById(android.R.id.tabhost);
//添加三个选项卡到tabhost上
addTab("conversation", "会话", R.drawable.tab_conversation, new Intent(
this, Conversation.class));
addTab("folder", "文件夹", R.drawable.tab_folder, new Intent(this,
Folder.class));
addTab("group", "群组", R.drawable.tab_group, new Intent(this,
Group.class));
}
/**
* 添加选卡到tabhost上
* @param tag 选项卡标签
* @param label 选项卡显示的名称
* @param iconId 选项卡的图标id
* @param intent 点击选项卡后跳转到的activity意图
*/
private void addTab(String tag, String label, int iconId, Intent intent) {
// 创建选项卡标签
TabSpec tabSpec = tabhost.newTabSpec(tag);
tabSpec.setIndicator(label, getResources().getDrawable(iconId));
// 设置选项卡所属的内容
tabSpec.setContent(intent);
// 将选项卡添加到tabwidget
tabhost.addTab(tabSpec);
}
}