編輯:進階開發
Android 的程式撰寫方式相當直覺,方便開發者快速實作各種功能。以下從頁籤的實作來看整個流程。
先建立 Android 專案,把 Activity 命名為 HelloTabWidget。接著在 main.xml(或自訂的 XML 檔)中建立一個 TabHost,它需要兩個元素:TabWidget 與 FrameLayout,通常會把這兩者放進 LinearLayout 裡。FrameLayout 作為切換內容用的容器。
要特別注意:TabWidget 與 FrameLayout 使用不同的 ID 命名空間,寫成 android:id="@android:id/xxx" 這個形式是必要的,TabHost 才能自動找到它們。另外,Activity 必須繼承 TabActivity。
<?XML version="1.0" encoding="utf-8"?>
<TabHost XMLns:android="https://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" />
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:id="@+id/textview1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="this is a tab" />
<TextView
android:id="@+id/textview2"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="this is another tab" />
<TextView
android:id="@+id/textview3"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:text="this is a third tab" />
</FrameLayout>
</LinearLayout>
</TabHost>
類別宣告要繼承 TabActivity:
public class HelloTabWidget extends TabActivity {
接著在 onCreate 中把頁籤掛上去:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mTabHost = getTabHost();
mTabHost.addTab(mTabHost.newTabSpec("tab_test1")
.setIndicator("TAB 1").setContent(R.id.textview1));
mTabHost.addTab(mTabHost.newTabSpec("tab_test2")
.setIndicator("TAB 2").setContent(R.id.textview2));
mTabHost.addTab(mTabHost.newTabSpec("tab_test3")
.setIndicator("TAB 3").setContent(R.id.textview3));
mTabHost.setCurrentTab(0);
}
newTabSpec 的參數是這個頁籤的 tag,setIndicator 決定標籤上顯示的文字(也可以傳入 View 做自訂樣式),setContent 則指定切到該頁時要顯示的內容——這裡直接指向 FrameLayout 中的某個子 View ID。實務上更常見的做法是把 setContent 指向一個 Intent,讓每個頁籤各自對應一個獨立的 Activity。
動手做一個 Android 貪食蛇:自訂 View 的繪製與刷新邏輯全解析
本文聚焦在 Android 的 UI 實作上,以經典的 Snake 貪食蛇專案為例,把自訂 View 的初始化、繪製與刷新機制講清楚。基本的操作這裡不多贅述,直接進主題。
探索最新的Android開發環境:從Windows Mobile程序員的視角
Android是Google開發的、以Linux平台為基礎的開源手機作業系統,開發語言以Java為主,這大幅降低了入門門檻,也拉高了它的使用率。 為什麼一個Window
Sidekick 的故事:從 Danger 到 Android(5)被微軟收購之後
2008 年 2 月,Danger 以 5 億美元賣給微軟 這筆交易發生在 Sidekick LX 剛發表之後。微軟當初承諾,會「結合 Danger 在行動消費市場近十年
獨家教程:用 PHP 撰寫 Android 應用程式
Google 的開源 Android 系統正在席捲智慧型手機市場。和 Apple 對上架 iPhone App Store 訂下嚴格規範不同,Android 平台開放得多