I'm trying to make tabs in a layout. I've found a lot of examples and tutorials using TabWidget
, TabHost
, but they all involve one of the following:
The content inside the tabs is static, so I should just be able to include everything in the layout, in pure XML.
Anyway to do that?
The simple answer, no. You have to setup your TabHost
in Java code and create your tabs. You can have static layouts for the tabs without using fragments but it still requires setup in Java.
If you don't do this setup in code, your TabWidget
won't know which layout corresponds to which tab and wouldn't be able to function. You're going to have to write a bit of code.
The code for doing this is really simple though.
The XML (placed inside your layout where you want it):
<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>
The Java code (placed wherever you setup your layout):
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);
OK, the best I found is this:
https://gist.github.com/jerolimov/618086
It still involves Java code, but there is no duplication of structure in the code, everything is in XML.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.