Androidアプリケーションでマルチビュー切替機能を実装する場合、TabHostコンポーネントが有効です。基本的な構成方法について解説します。
レイアウトXMLでは、親コンテナとしてTabHostを使用し、内部にタブ見出し表示用のTabWidgetとコンテンツ表示領域のFrameLayoutを配置します。
<?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="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TabWidget
android:id="@android:id/tabs"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<FrameLayout
android:id="@android:id/tabcontent"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</TabHost>
実装コードでは、TabActivityを継承したメインアクティビティでタブ設定を行います。各タブは別個のアクティビティと紐付けられます。
public class TabbedMainActivity extends TabActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.tab_container);
TabHost container = getTabHost();
// システム情報タブの構築
TabHost.TabSpec systemTab = container.newTabSpec("sys_tab")
.setIndicator("システム情報", null)
.setContent(new Intent(this, SystemInfoActivity.class));
// ハードウェア状態タブの構築
TabHost.TabSpec hardwareTab = container.newTabSpec("hw_tab")
.setIndicator("ハードウェア状態", null)
.setContent(new Intent(this, HardwareStatusActivity.class));
// 操作履歴タブの構築
TabHost.TabSpec historyTab = container.newTabSpec("op_tab")
.setIndicator("操作履歴", null)
.setContent(new Intent(this, OperationHistoryActivity.class));
// タブの登録と初期選択設定
container.addTab(systemTab);
container.addTab(hardwareTab);
container.addTab(historyTab);
container.setCurrentTab(0);
}
}
タブの追加順序が表示順序に反映されるため、意図した順番でaddTab()を呼び出します。setCurrentTab()メソッドで起動時のデフォルトタブを指定可能です。各タブコンテンツは独立したアクティビティとして実装し、画面遷移の管理をTabHostに委ねることができます。