頁籤

實作說明:新增專案後,將MainActivity的繼承從Activity改為TabActivity, 另外新增3個Activity分別為FirstActivity、SecondActivity、ThirdActivity

<!--activity_main.xml-->

<?xml version="1.0" encoding="utf-8"?>

<TabHost

android:id="@android:id/tabhost"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

xmlns:android="http://schemas.android.com/apk/res/android">

<LinearLayout

android:orientation="vertical"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:padding="5dp">

<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"

android:padding="5dp">

<TextView android:id="@+id/txt1"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:text="@string/tab_01"/>

<TextView android:id="@+id/txt2"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:text="@string/tab_02"/>

<TextView android:id="@+id/txt3"

android:layout_width="fill_parent"

android:layout_height="fill_parent"

android:text="@string/tab_03"/>

</FrameLayout>

</LinearLayout>

</TabHost>

/*MainActivity.java*/

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

Resources res = getResources();

//取得Layout activity_main中的tabhost

TabHost host = getTabHost();

TabSpec spec;

//Tab01

spec = host

.newTabSpec(res.getString(R.string.tab_01))

.setIndicator(res.getString(R.string.tab_01),

res.getDrawable(R.drawable.ic_launcher))

.setContent(new Intent(this, FirstActivity.class));

host.addTab(spec);

//Tab02

spec = host

.newTabSpec(res.getString(R.string.tab_02))

.setIndicator(res.getString(R.string.tab_02),

res.getDrawable(R.drawable.ic_launcher))

.setContent(new Intent(this, SecondActivity.class));

host.addTab(spec);

//Tab03

spec = host

.newTabSpec(res.getString(R.string.tab_03))

.setIndicator(res.getString(R.string.tab_03),

res.getDrawable(R.drawable.ic_launcher))

.setContent(new Intent(this, ThirdActivity.class));

host.addTab(spec);

//設定tab顯示頁籤

host.setCurrentTab(1);

//TabHost事件

host.setOnTabChangedListener(new OnTabChangeListener() {

@Override

public void onTabChanged(String tabId) {

// TODO Auto-generated method stub

Toast.makeText(MainActivity.this, tabId, Toast.LENGTH_SHORT).show();

}

});

}

設定FirstActivity、SecondActivity、ThirdActivity

<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"

android:background="#ff0000">

</RelativeLayout>