TabHost, Tabspec

タブ付きビューの作り方。

  • 基本系
public class Tabs1 extends TabActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);        TabHost tabHost = getTabHost();
        tabHost.addTab(tabHost.newTabSpec("tab1")
                .setIndicator("tab1")
                .setContent(R.id.tab1));
    }
}
  • TabHost.addTab(TabHost.TabSpec)…指定したTabSpecでタブを作成する
  • TabHost.newTabSpec("tab1")…指定したID(この場合「tab1」)でTabSpecオブジェクトを新規作成する
  • TabSpec.setIndicator(String), TabSpec.setIndicator(View), TabSpec.setIndicator(CharSequence label, Drawable icon)…タブ見出しに指定の文字列/ビュー/画像と文字を設定する。Indicatorというのはタブの見出しの部分のこと。
  • TabSpec.setContent()…タブに表示する中身を指定。引数の指定は3通り。
    • setContent(int viewId)
    • setContent(Intent intent)
    • setContent(TabHost.TabContentFactory contentFactory)

1つ目はR.layoutとかを指定する、ActivityのsetContentViewに似た使い方。2番目のはstartActivity(Intent)のような使い方。3個目はよくわからないけどTabHost.TabContentFactoryを指定できる。

Makes the content of a tab when it is selected. Use this if your tab content needs to be created on demand, i.e. you are not showing an existing view or starting an activity.

TabCotentFactoryはcreateTabContent(String tag)という抽象メソッドを1個持つのみ(返り値はView)。前者2つの呼び出しは独立したアクティビティを指定するので、たぶん?複数のタブでデータを共有するような複雑なビューを書くときとかに使うのかもしれない。