2010年5月23日 星期日

Android TabLayout 使用心得

Android 2.2 SDK 己經出了…
http://developer.android.com/sdk/index.html
最近也在學習,還好之前有 java/javaME 的基礎,還算順利。

Google 官方有提供教學網頁…
http://developer.android.com/resources/index.html 
很不錯。

不過其中一個範例 TabLayout 的使用…
 http://developer.android.com/resources/tutorials/views/hello-tabwidget.html
這個範例對初學者來講比較複雜。

底下是比較簡單易理解的版本…

HelloTabWidgetNoIcon.java

package com.study.HelloTabWidgetNoIcon;

import android.app.TabActivity;
import android.os.Bundle;
import android.widget.TabHost;

public class HelloTabWidgetNoIcon extends TabActivity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);

TabHost tabHost = getTabHost(); // The activity TabHost
TabHost.TabSpec spec; // Resusable TabSpec for each tab

// Initialize a TabSpec for each tab and add it to the TabHost
spec = tabHost.newTabSpec("artists").setIndicator("Artists").setContent(R.id.tab0);
tabHost.addTab(spec);

// Do the same for the other tabs
spec = tabHost.newTabSpec("albums").setIndicator("Albums").setContent(R.id.tab1);
tabHost.addTab(spec);

spec = tabHost.newTabSpec("songs").setIndicator("Songs").setContent(R.id.tab2);
tabHost.addTab(spec);

tabHost.setCurrentTab(0);
}
}


main.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"
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:text="tab0"
android:id="@+id/tab0"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:text="tab1"
android:id="@+id/tab1"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView
android:text="tab2"
android:id="@+id/tab2"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />

</FrameLayout>
</LinearLayout>
</TabHost>


對照一下 HelloTabWidgetNoIcon.java 及 main.xml 就可以了解程式碼跟 layout 間的對應關係了(tab0,tab1,tab2)。

跟官方的範例不同的地方在於,官方的還多加了…
一、Tab 的小圖示( ic_tab_artists.xml, ic_tab_albums.xml, ic_tab_songs.xml 及圖片 )
二、動態的 Tab View ( ArtistsActivity.java, AlbumsActivity.java, SongsActivity.java )
所以才比較複雜並且要多撰寫一些 xml 碼。

不過,若真的要用在手機上,當然還是用圖示比較吸引人嘍。

沒有留言:

更高效處理 micro second 的方式

更高效處理 micro second 的方式…  以 STM32 為例… __IO unsigned long sys_tick = 0; void SysTick_Handler(void) {     HAL_IncTick();     sys_tick += (SysTi...