import android.os.Bundle; import android.app.Activity; import android.app.TabActivity; import android.content.Intent; import android.view.Menu; import android.widget.TabHost; import android.widget.TabHost.TabSpec; public class MainActivity extends TabActivity { private TabHost m_tabHost; /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); //getTabHost返回的TabHost用于装载tabs m_tabHost = getTabHost(); //add tabs,这里用于添加具体的Tabs,并用Tab触发相应的Activity addOneTab(); addTwoTab(); addThreeTab(); addFourTab(); } public void addOneTab(){ Intent intent = new Intent(); intent.setClass(MainActivity.this, OneActivity.class); TabSpec spec = m_tabHost.newTabSpec("One"); spec.setIndicator(getString(R.string.one), null); spec.setContent(intent); m_tabHost.addTab(spec); } public void addTwoTab(){ Intent intent = new Intent(); intent.setClass(MainActivity.this, TwoActivity.class); TabSpec spec = m_tabHost.newTabSpec("Two"); spec.setIndicator(getString(R.string.two), null); spec.setContent(intent); m_tabHost.addTab(spec); } public void addThreeTab(){ Intent intent = new Intent(); intent.setClass(MainActivity.this, ThreeActivity.class); TabSpec spec = m_tabHost.newTabSpec("Three"); spec.setIndicator(getString(R.string.three), null); spec.setContent(intent); m_tabHost.addTab(spec); } public void addFourTab(){ Intent intent = new Intent(); intent.setClass(MainActivity.this, FourActivity.class); TabSpec spec = m_tabHost.newTabSpec("Four"); spec.setIndicator(getString(R.string.four), null); spec.setContent(intent); m_tabHost.addTab(spec); } }
XML布局文件:
<?xml version="1.0" encoding="utf-8"?> <TabHost xmlns:android="http://schemas.android.com/apk/res/android" android:id="@android:id/tabhost" android:layout_width="fill_parent" android:layout_height="fill_parent"> <LinearLayout android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent"> <TabWidget android:id="@android:id/tabs" android:layout_width="fill_parent" android:layout_height="wrap_content" android:paddingLeft="1dip" android:paddingRight="1dip" android:paddingTop="4dip" /> <FrameLayout android:id="@android:id/tabcontent" android:layout_width="fill_parent" android:layout_height="0dip" android:layout_weight="1" /> </LinearLayout> </TabHost>
注意:每一个Activity都要在配置文件中注册