1. 新建主界面
<RelativeLayout 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"
tools:context=".MainActivity" >
<TabHost
android:id="@+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" />
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<!-- 第一个标签 -->
<LinearLayout
android:id="@+id/content1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#ff0000"
android:orientation="vertical" >
</LinearLayout>
<!-- 第二个标签 -->
<LinearLayout
android:id="@+id/content2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#f0f000"
android:orientation="vertical" >
</LinearLayout>
<!-- 第三个标签 -->
<LinearLayout
android:id="@+id/content3"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#0000ff"
android:orientation="vertical" >
</LinearLayout>
</FrameLayout>
</LinearLayout>
</TabHost>
</RelativeLayout>
2.新建MainActivity
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.TabHost;
public class MainActivity extends Activity
{
private TabHost tabHost;
@Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initViews();
}
private void initViews()
{
Button button1 = new Button(this);
button1.setText("标签1");
tabHost = (TabHost) findViewById(R.id.tabHost);
tabHost.setup();
tabHost.addTab(tabHost.newTabSpec("tab1").setIndicator(button1).setContent(R.id.content1));
tabHost.addTab(tabHost.newTabSpec("tab2").setIndicator("标签2").setContent(R.id.content2));
tabHost.addTab(tabHost.newTabSpec("tab3").setIndicator("标签3").setContent(R.id.content3));
}
}
tabHost.newTabSpec("tab1") 里面参数是为了tabHost内部区别使用
在这里tabHost的 id 是使用的自定义的 id 并且 MainActivity是继承的原生的Activity
setIndicator(button1) 使用自定义的 View 作为标签形式
setIndicator("标签2") 使用系统默认的tab标签形式 并设置文字为:”标签2“
下一章将说明第二种tabHost的使用方法。