如何使用XML完全创建带有选项卡的布局?

时间:2013-03-14 20:45:45

标签: android xml layout tabs

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

  • 活动中的Java代码
  • 每个标签的单独活动
  • 为每个标签分隔片段

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

无论如何要做到这一点?

2 个答案:

答案 0 :(得分:12)

简单的回答,没有。您必须在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);

答案 1 :(得分:0)

好的,我找到的最好的是:

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

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

相关问题