如何在 Android 中使用 TabHost?
在進入示例之前,我們應該瞭解 Android 中的 TabHost 是什麼。TabHost 包含一組選項卡。每個選項卡根據專案規範包含片段或活動。使用者可以從左到右或從右到左滾動選項卡。
此示例演示如何在 Android 中使用 TabHost。
步驟 1 - 在 Android Studio 中建立一個新專案,轉到檔案 ⇒ 新建專案,並填寫所有必需的詳細資訊以建立一個新專案。
步驟 2 - 將以下程式碼新增到 res/layout/activity_main.xml 中。
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" tools:context=".MainActivity"> <TabHost android:id="@+id/tabhost" android:layout_width="match_parent" android:layout_height="match_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"> <LinearLayout android:id="@+id/tab1" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:id="@+id/button" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="tab1" /> </LinearLayout> <LinearLayout android:id="@+id/tab2" android:layout_width="match_parent" android:layout_height="match_parent"> <Button android:id="@+id/button2" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="tab2" /> </LinearLayout> </FrameLayout> </LinearLayout> </TabHost> </LinearLayout>
在上面的佈局中,我們聲明瞭 FrameLayout 作為 Tab 元件的子項(根據 android.com,它需要 FrameLayout 作為 Tab 元件的內容)。
步驟 3 - 將以下程式碼新增到 src/MainActivity.java 中
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.widget.RadioButton;
import android.widget.TabHost;
public class MainActivity extends AppCompatActivity {
RadioButton radioButton;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
TabHost tabs = (TabHost) findViewById(R.id.tabhost);
tabs.setup();
TabHost.TabSpec spec = tabs.newTabSpec("tag1");
spec.setContent(R.id.tab1);
spec.setIndicator("First");
tabs.addTab(spec);
spec = tabs.newTabSpec("tag2");
spec.setContent(R.id.tab2);
spec.setIndicator("second");
tabs.addTab(spec);
}
}步驟 4 - 無需更改 manifest.xml 檔案。
讓我們嘗試執行您的應用程式。我假設您已將您的實際 Android 移動裝置連線到您的計算機。要從 Android Studio 執行應用程式,請開啟專案的一個活動檔案,然後單擊工具欄中的執行
圖示。選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示您的預設螢幕。

現在點選第二個選項卡。它應該會顯示如下結果 -

廣告
資料結構
網路
關係型資料庫管理系統
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP