[英]How can I create a layout with tabs completely in XML?
我正试图在布局中制作标签。 我发现了很多的使用示例和教程TabWidget
, TabHost
,但它们都涉及下列之一:
选项卡内的内容是静态的,所以我应该能够在纯XML中包含布局中的所有内容。
无论如何要这样做?
简单的答案,没有。 您必须在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);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.