レイアウトにタブを作成しようとしています。TabWidget
、を使用した多くの例とチュートリアルを見つけましたTabHost
が、それらはすべて次のいずれかを含みます。
- アクティビティの Java コード
- タブごとに個別のアクティビティ
- タブごとに個別のフラグメント
タブ内のコンテンツは静的なので、純粋な XML ですべてをレイアウトに含めることができるはずです。
とにかくそうするには?
簡単な答えはありません。JavaコードでセットアップTabHost
し、タブを作成する必要があります。フラグメントを使用せずにタブの静的レイアウトを作成できますが、それでもJavaでセットアップする必要があります。
この設定をコードで行わないと、TabWidget
どのレイアウトがどのタブに対応しているかわからず、機能できなくなります。少しコードを書く必要があります。
ただし、これを行うためのコードは非常に単純です。
XML(レイアウト内の必要な場所に配置):
<TabHost android:id="@+id/tab_host"
android:layout_width="fill_parent"
android:layout_height="wrap_content" >
<LinearLayout android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<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="wrap_content">
<LinearLayout
android:id="@+id/tab_one_container"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
<LinearLayout
android:id="@+id/tab_two_container"
android:layout_width="fill_parent"
android:layout_height="wrap_content" />
</FrameLayout>
</LinearLayout>
</TabHost>
Javaコード(レイアウトを設定する場所に配置):
TabHost host = (TabHost)findViewById(R.id.tab_host);
host.setup();
TabSpec spec = host.newTabSpec("Tab One");
spec.setContent(R.id.tab_one_container);
spec.setIndicator("Tab One");
host.addTab(spec);
spec = host.newTabSpec("Tab Two");
spec.setContent(R.id.tab_two_container);
spec.setIndicator("Tab Two");
host.addTab(spec);
OK、私が見つけた最高のものはこれです:
https://gist.github.com/jerolimov/618086
これにはまだ Java コードが含まれますが、コード内に構造の重複はなく、すべてが XML です。