//切记不要使用大图片
public class Tab1Activity extends Activity {
private TabHost tabHost; //准备TabHost 管理
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_tab1);
tabHost = (TabHost)findViewById(R.id.TabHost); //tabhost
tabHost.setup(); //一定要写这步骤
addTab();//初始化选项卡
// 设置TabHost背景颜色
tabHost.setBackgroundColor(Color.argb(150, 20, 80, 150));
// 设置TabHost背景图片资源
tabHost.setBackgroundResource(R.drawable.ic_launcher);
// 设置当前显示哪一个标签
tabHost.setCurrentTab(0);
// 标签切换事件处理,setOnTabChangedListener 标签切换事件
tabHost.setOnTabChangedListener(new OnTabChangeListener() {
@Override
public void onTabChanged(String tabId) {
Toast.makeText(Tab1Activity.this, "tabid:"+tabId, 0).show();
}
});
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.tab1, menu);
return true;
}
// 为TabHost添加标签 新建一个newTabSped(new TabSpec) 设置其标签和图标(setIndicator)、设置内容(setContent)
private void addTab() {
tabHost.addTab(tabHost.newTabSpec("java").setIndicator("Java之路",
getResources().getDrawable(R.drawable.ic_launcher))
.setContent(R.id.javaWorker));
// 指定内容为一个TextView --->public TabHost.TabSpec setContent(int viewId) 此方法需要一个 viewId 作为参数
tabHost.addTab(tabHost.newTabSpec("android").setIndicator("Android之路",
getResources().getDrawable(R.drawable.ic_launcher))
.setContent(R.id.androidWorker));
tabHost.addTab(tabHost.newTabSpec("math").setIndicator("算法之路",
getResources().getDrawable(R.drawable.ic_launcher))
.setContent(R.id.systemWorker));
}
}
xml布局如下:
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+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" />
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView android:id="@+id/javaWorker"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="java工程师"
android:textColor="#FF0000"/>
<TextView android:id="@+id/androidWorker"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="android工程师"
android:textColor="#385E0F"/>
<TextView android:id="@+id/systemWorker"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:text="系统分析师"
android:textColor="#1E90FF"/>
</FrameLayout>
</LinearLayout>
</TabHost>