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

11

我正在尝试在布局中创建选项卡。我发现了很多使用 TabWidgetTabHost 的示例和教程,但它们都涉及以下之一:

  • 在活动中编写Java代码
  • 为每个选项卡分别创建活动
  • 为每个选项卡分别创建片段

选项卡内的内容是静态的,所以我应该只需将所有内容以纯XML形式包含在布局中。

是否有任何方法实现这一点?


3
在某个时候你必须要写一些代码- XML 文件无法知道在标签被点击时该如何切换并执行相应的操作。你可以避免使用像活动/碎片这样重量级的代码,但是这并不意味着可以完全不写代码。 - Gabe Sechan
2个回答

13
简短回答是不行的。您必须在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);

那有点糟糕。为什么我不能引用选项卡中布局的ID来连接它们呢?我不介意编写代码,但我觉得在代码中放置链接有些不合适。 - erwan
1
你不能这样做,因为Google没有将它写入SDK中。我希望我能给你一个更好的答案,但当你使用别人的框架时,你就会受到他们设定的限制。这只是其中之一。 - Michael Celey

0

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接