11

我正在尝试在布局中制作标签。我找到了很多使用TabWidget,的示例和教程TabHost,但它们都涉及以下内容之一:

  • 活动中的 Java 代码
  • 每个选项卡的单独活动
  • 每个选项卡的单独片段

选项卡内的内容是静态的,所以我应该能够在布局中包含纯 XML 中的所有内容。

无论如何要这样做?

4

2 回答 2

13

简单的答案,不。您必须设置您TabHost的 Java 代码并创建您的选项卡。您可以在不使用片段的情况下为选项卡设置静态布局,但仍然需要在 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);
于 2013-03-14T20:51:52.897 回答
0

好的,我发现的最好的是:

https://gist.github.com/jerolimov/618086

它仍然涉及Java代码,但代码中没有重复结构,一切都在XML中。

于 2013-03-16T09:39:28.197 回答