I am beginning with Android and I'd like to add tabs to my existing application.
Right now I just have one activity with the layout defined in the XML file. I would now like to add other tabs.
I have looked it up and found http://developer.android.com/resources/tutorials/views/hello-tabwidget.html on the Android developer site; however, that doesn't use XML for defining the layout of the tabs.
So, how can I easily add tabs using the XML file only for the layout?
Thanks in advance.
The
TabWidget
implementation is pretty rigid -- you don't have much control over layout.If you want to create your own custom tabs, your best bet is to create a custom layout and call it from the activities that you want to have these "tabs". You can call reusable layouts in XML with
<include layout="@layout/my_tab_layout" />
and then write your own initialization code in a reusable class.I've run into a situation where the TabWidget layout didn't do what I needed, so I faked it up with a ViewFlipper and a RadioGroup. That way, I could define the content of the tabs (each view in the ViewFlipper) using includes (like in Farray's answer).
The tabs themselves were the RadioButtons in the RadioGroup - you just have an OnCheckedChangeListener in your code and set the ViewFlipper's displayed child accordingly. You can define the RadioButton layout in XML (with text or images or whatever).
Here's a pseudo-layout where the tabs use images:
And here's the listener:
Yes, it does. See step #4.
UPDATE
Google reorganized their documentation and got rid of this tutorial. You can see the use of XML for defining the tabs in
TabWidget
in this sample project.