Android SDK 提供了元件可以在 Activity 中建立容易管理的 Tab Page,以下介紹 Tab Page 的初階使用方法

首先需要一個 TabHost 元件,負責管控整個 Tab Page 的架構

再來需要一個 TabWidget 元件,控制所有的 Tab 標籤

最後還需要 FrameLayout  元件,負責顯示 Tab 標籤中的頁面

 

假設程式中需要有兩個標籤,tab1 用TableLayout 寫成,tab2則用 RelativeLayout 寫成,則 layout.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"
>
<TabWidget android:id="@android:id/tabs"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
/>
<FrameLayout android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
         <TableLayout android:id="@+id/tab1"
android:layout_width="200dp"
android:layout_height="fill_parent"
android:layout_gravity="center_horizontal"
android:paddingTop="70dp"
>
.....
         </TableLayout>
         <RelativeLayout android:id="@+id/tab2"
android:layout_width="400dp"
android:layout_height="fill_parent"
android:layout_gravity="center_horizontal"
android:paddingTop="70dp"
>
....
         </RelativeLayout>
</FrameLayout>
</TabHost>

 

最外層由 TabHost 包起來,接下來是 TabWiget 元件還有 FrameLayout 元件,其中兩個 tab 的顯示元件都放在 Framelayout 中

要注意以下幾點:

1. <TabWidget> 的 id 一定要是 @android:id/tabs

2. <FrameLayout> 的 id 一定要是 @android:id/tabcontent

3. FrameLayout 中的每一個顯示元件一定要設 android:paddingTop 屬性,以免與 Tab 標題重疊

 

程式中的寫法如下:

 

Create TabHost 元件並初始化:

TabHost tabHost = (TabHost)findViewById(R.id.tabHost);
tabHost.setup();

 

建立 Tab page 並設定標題及介面元件,然後將之家道 TabHost 中

TabSpec spec=tabHost.newTabSpec("tab1");
spec.setContent(R.id.tab1);
spec.setIndicator(getString(R.string.tab_1_title));
tabHost.addTab(spec);

spec=tabHost.newTabSpec("tab2");
spec.setIndicator(getString(R.string.tab_2_title));
spec.setContent(R.id.tab2);
tabHost.addTab(spec);

 

設定 default 顯示的 tabe page:

tabHost.setCurrentTab(0);

 

此外,可以利用以下程式碼分別改變 tab page 的字體大小:

TabWidget tabWidget = (TabWidget)tabHost.findViewById(android.R.id.tabs);

View tabView = tabWidget.getChildTabViewAt(0);
TextView tab = (TextView)tabView.findViewById(android.R.id.title);
tab.setTextSize(30);

tabView = tabWidget.getChildTabViewAt(1);
tab = (TextView)tabView.findViewById(android.R.id.title);
tab.setTextSize(20);

 

以上~~只是 tab page 初階用法,缺點是所有的程式碼都要放在同一個檔案中,比較難維護

之後會介紹更 tab page 進階的用法!

你說要等多久?

幹你娘我哪知道

arrow
arrow
    全站熱搜

    擒猿小舖 發表在 痞客邦 留言(1) 人氣()