In my previous post I demonstrated using the “out of the box” tabs in an Android application. While this is useful for a basic layout, you quickly come to the conclusion that, frankly, the tabs are hideous and that you need to exert some level of customization over them.
The short answer is that Android does support a deep level of control over the look and feel of the tabs, however, as part of the long answer, this ability has only existed since API Level 4 (Android 1.6). While this means that your application cannot target Android 1.5 and below. This is an acceptable compromise, recent studies have shown that the dominant Android OS version is 2.x.
Our base code will the be the same as the end result from the previous post, I will demonstrate how to take this code and use XML to define what the tab looks like. Here is our end code, for reference.
Running this code yields the following output:
Note: I did change the background color from the previous example
Very unsightly. Lets restructure the the tabs to make them look nicer. How about this:
Looks a lot nicer right? So how did we do this, well I first I added a couple things to our project. The first was a new XML file to house the layout for each tab, the XML is shown below:
As with any layout XML in Android, you can do whatever you like with this, for this example, I am keeping things simple. We have a simple TextView within a standard LinearLayout view group.
The second thing was an image called “tab_divider.png” (available in the source). This is used to separate the tabs in the view.
Here is our updated code for the Activity:
The first thing I will point is the setting of the divider. This step is NOT required, however it really adds to the look of the tabs and helps the user separate them, you mileage may very. This MUST be called at this point, if you do not call it first you will not see your divider.
Ok the important stuff here is the inflated view we are using (R.layout.tab_content) defines the layout of each of the tabs. You could use “n” views here if you wanted, I simply chose to use the same view for each and update the TextView using findViewById method. It is required that you re-inflate the view each time you wish to use it. Not doing so will cause you to get errors concerning the parent view.
Once you inflate the view and set the various properties as desired, you call the setIndicator(View view) overload. This overload is only available in API Level 4 and above (that is Android 1.6).
As you can see, taking this step is very easy and straightforward and allows for an impressive amount of customization.
At this point, you have now completed the process of customizing the look of the tabs. However, if you run the application you may notice that as you switch between tabs, there is no indicator of which tab is selected. That will be the subject of the next entry, I will only say at this point that it involves: State-Lists.