我正在尝试在布局中制作标签。我使用TabWidget
,TabHost
找到了很多示例和教程,但它们都涉及以下内容之一:
标签内的内容是静态的,所以我应该能够在纯XML中包含布局中的所有内容。
无论如何要做到这一点?
答案 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)