タブメニューはTabActivityを継承することで実装します(継承しなくても実装できます)。setIndicatorでタブのレイアウト、setContentでタブに対応する画面のレイアウトを設定します。また、タブ切り替えはOnTabChangeListenerを実装することで取得できます。
import android.app.TabActivity;
import android.widget.TabHost;
import android.widget.TabHost.TabSpec;
import android.widget.TabHost.OnTabChangeListener;
public class MyClass extends TabActivity implements OnTabChangeListener{
public void myMethod(){
TabHost tabHost = this.getTabHost();
// TabActivityを継承しない場合
//TabHost tabHost = (TabHost)findViewById(android.R.id.tabhost);
// "first"というメニュータブ
TabSpec firstTab = tabHost.newTabSpec("first");
firstTab.setIndicator("first",getResources().getDrawable(R.drawable.tab_first));
firstTab.setContent(R.id.content_first);
// "second"というメニュータブ
TabSpec secondTab = tabHost.newTabSpec("second");
secondTab.setIndicator("second",getResources().getDrawable(R.drawable.tab_second));
secondTab.setContent(R.id.content_second);
// secondTab.setIndicator(new TextView(this)); // 直接レイアウトを設定
// secondTab.setContent(new TextView(this)); // 直接レイアウトを設定
tabHost.addTab(firstTab);
tabHost.addTab(secondTab);
tabHost.setCurrentTab(0); // カレントを設定
tabHost.setOnTabChangedListener(this); // リスナーを設定
}
public void onTabChanged(String tabId){
switch(tabId){
case "first":
case "second":
}
}
レイアウトのxmlでは各メニューに対応した画面のレイアウトを設定しますが、若干の決まりごとがあります。
1) idがtabhostのTabHostタグを作る。
2) TabHostの中に、verticalなLinearLayoutを作る。*1
3) LinearLayoutの中に、idがtabsのTabWidgetタグを作る。
4) LinearLayoutの中に、idがtabcontentのFrameLayoutを作る。
5) FrameLayoutの中に、各メニューに対応した画面のレイアウトを作る
res/layout/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:layout_width="fill_parent" android:layout_height="fill_parent" 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="fill_parent" > <!-- firstの画面 --> <LinearLayout android:id="@+id/content_first" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:text="tab_first" /> </LinearLayout> <!-- secondの画面 --> <LinearLayout android:id="@+id/content_second" android:layout_width="fill_parent" android:layout_height="fill_parent" > <TextView android:text="tab_second" /> </LinearLayout> </FrameLayout> </LinearLayout> </TabHost>
タブメニューアイコンファイル
res/drawable/tab_first.png
res/drawable/tab_second.png
*1:TabHostがFrameLayoutであるため、タブコンテンツがタブとかぶって表示されてしまう。


コメント