Free Online Courses for Software Developers - MrBool
× Please, log in to give us a feedback. Click here to login
×

You must be logged to download. Click here to login

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

×

MrBool is totally free and you can help us to help the Developers Community around the world

Yes, I'd like to help the MrBool and the Developers Community before download

No, I'd like to download without make the donation

How to Customize Tab Layout in Android

In android there are many layouts available for a developer to represent maximum functionality with vivid User Interface (UI). Tab Layout is also one of them. In this topic customization of Tab Layout will be covered.

Introduction

In android there are many layouts available for a developer to represent maximum functionality with vivid User Interface (UI). Tab Layout is also one of them. In Tab Layout there are multiple tabs which holds one activity in each one tab. Simply user will get four activities on only one activity contains tabs. Current activity in Tab Layout will appear as per tab clicked. In this topic customization of Tab Layout will be covered.

Classes used in this topic:

  • TabHost
  • TabWidget
  • TabHost.TabSpec
  • FrameLayout
  • Intent

Objective:

  • To give brief explanation how Tab Layout works.
  • Introduction to TabHost.TabSpec class and its methods
  • Dynamically Customization of Tab Layout in java class.

Introduction to classes used:

  • TabHost: Tabhost class used to wrap the tabbed window view. It can hold upto 2 children:
    • One is the set of tab labels which will be clicked by the user to activate specific tab.
    • Second is the FrameLayout which is used to show the contents of activated tab.
  • TabWidget: This class is used to hold the Tabs and having parent TabHost. When user select a tab it will give messege to the TabHost to switch displayed activity.
  • TabHost.TabSpec: This class is used to give indicator like labels of the Tab, Content and Tag are also provided by this class.
  • FrameLayout: FrameLayout class is used to show the contents of the selected tab.
  • Intent: This class is used to setup the Activity, when user click on any of unselected tab then this will shift to the current selected activity.

Interaces used:

TabHost.OnTabChangeListener: This listener is used to listen the event at runtime when user will shift to the other tab from the current activated tab. It contains the following methods which can be defined as per need.

abstract void onTabChanged(String tabId):This method is used to handle the event when user click on another tab from current activated tab. It has no return type and having one argument which is String tabId. This argument is used to match the id of current selected tab.

Steps Involved:

Step 1: Create a new project in eclipse with name TabCustomization and package should be “com.nkm.tabcustomization”.

Creating a new project in eclipseCreating a new project in eclipse

Figure 1: Creating a new project in eclipse

Step 2: Create a folder named as drawable inside the resource folder. To create this folder you have to right click on the res folder then choose New then Folder from menu as shown in screen below.

 Creting a new folder

Figure 2: Creting a new folder

Step 3: Now right click on the drawable folder and choose new Android XML File option.

Choosing new Android XML File option

Figure 3: Choosing new Android XML File option

Step 4: Give name tab_selector to Android XML File then paste the following code into it.

Listing 1: Giving name tab_selector to Android XML File

<?xml version="1.0" encoding="utf8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <! When selected, use grey >
    <item android:drawable="@drawable/tabselectedcolor" android:state_selected="true"/>
    <! When not selected, use white >
    <item android:drawable="@drawable/tabunselcolor"/>

</selector>

Step 5: As before create Android XML File inside the drawable folder and give name to it tabselectedcolor and paste the following code into it.

Listing 2: Creating Android XML File inside the drawable folder

<?xml version="1.0" encoding="utf8" ?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >

    <solid android:color="#00dcee" />

</shape>

Step 6: Create another Android XML File inside the drawable folder and give name to it tabunselcolor and paste the following code into it.

Listing 3: Creating another Android XML File inside the drawable folder

<?xml version="1.0"  encoding="utf8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >

    <solid android:color="#ffffff" />

</shape>

Step 7: Paste the following code inside the main.xml file

Listing 4: main.xml code

<?xml version="1.0" encoding="utf8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/host"
    android:layout_width="fillparent"
    android:layout_height="fillparent" >

    <RelativeLayout
        android:layout_width="fillparent"
        android:layout_height="fillparent"
        android:orientation="vertical"
        android:padding="6dp" >

        <TabWidget
            android:id="@android:id/tab"
            android:layout_width="fillparent"
            android:layout_height="wrapcontent" />

        <FrameLayout
            android:layout_below="@android:id/tab"
            android:id="@android:id/tabattributes"
            android:layout_width="fillparent"
            android:layout_height="fillparent"
            android:padding="6dp" />
    </RelativeLayout>

</TabHost>

Step 8: Paste the following code inside the TabCustomizationActivity.java.

Listing 5: TabCustomizationActivity.java.

package com.nkm.tabcustomization;

import android.app.TabActivity;
import android.content.Intent;
import android.content.res.Resources;
import android.graphics.Color;
import android.os.Bundle;
import android.widget.TabHost;
import android.widget.TabHost.OnTabChangeListener;

public class TabCustomizationActivity extends TabActivity implements
		OnTabChangeListener {
	/** Called when the activity is first created. */
	TabHost tHost;

	@Override
	public void onCreate(savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.main);
		Resources resources = getResources();

		tHost = getTabHost();
		TabHost.TabSpec tSpec;
		Intent intent;

		intent = new Intent().setClass(this, FirstActivity.class);

		tSpec = tHost.newTabSpec("first").setIndicator("One")
				.setContent(intent);
		tHost.addTab(tSpec);

		intent = new Intent().setClass(this, FirstActivity.class);
		tSpec = tHost.newTabSpec("second").setIndicator("Second")
				.setContent(intent);
		tHost.addTab(tSpec);

		intent = new Intent().setClass(this, FirstActivity.class);
		tSpec = tHost.newTabSpec("third").setIndicator("Third")
				.setContent(intent);
		tHost.addTab(tSpec);

		tHost.setCurrentTab(0); // Default Selected Tab

		tHost.setOnTabChangedListener(this);

		tHost.getTabWidget().getChildAt(0).getLayoutParams().height = 40;
		tHost.getTabWidget().getChildAt(0).setBackgroundColor(Color.WHITE);
		tHost.getTabWidget().getChildAt(1).getLayoutParams().height = 40;
		tHost.getTabWidget().getChildAt(1).setBackgroundColor(Color.WHITE);
		tHost.getTabWidget().getChildAt(2).getLayoutParams().height = 40;
		tHost.getTabWidget().getChildAt(2).setBackgroundColor(Color.WHITE);

		tHost.getTabWidget().getChildAt(0)
				.setBackgroundColor(Color.rgb(00, 219, 239));

	}

	@Override
	public void onTab(String tabId) {
		if (tabId.equals("first")) {
			tHost.getTabWidget().getChildAt(0)
					.setBackgroundResource(R.drawable.tab_selector);
			tHost.getTabWidget().getChildAt(1).setBackgroundColor(Color.WHITE);
			tHost.getTabWidget().getChildAt(2).setBackgroundColor(Color.WHITE);
		} else if (tabId.equals("second")) {
			tHost.getTabWidget().getChildAt(1)
					.setBackgroundResource(R.drawable.tab_selector);

			tHost.getTabWidget().getChildAt(0).setBackgroundColor(Color.WHITE);
			tHost.getTabWidget().getChildAt(2).setBackgroundColor(Color.WHITE);
		} else if (tabId.equals("third")) {
			tHost.getTabWidget().getChildAt(2)
					.setBackgroundResource(R.drawable.tab_selector);
			tHost.getTabWidget().getChildAt(1).setBackgroundColor(Color.WHITE);
			tHost.getTabWidget().getChildAt(0).setBackgroundColor(Color.WHITE);
		}

	}

}

Step 9: Create another class inside the com.nkm.tabcustomization and paste the following code inside it.

Listing 6: Creating another class inside the com.nkm.tabcustomization

package com.nkm.tabcustomization;

import android.app.Activity;
import android.os.Bundle;
import android.widget.TextView;

public class FirstActivity extends Activity{
	TextView showText;
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Autogenerated method stub
		super.onCreate(savedInstanceState);
		showText = new TextView(this);
		showText.setText("See above Tab Customization");
		setContentView(showText);	
	}
}

Step 10: Run your project you will get results as shown below:

First tab selected

Figure 4: First tab selected

First Tab selected with specified color given to it while other tabs are unselected

Second tab selected
Figure 5: Second tab selected

Second tab is selected with changed specified color while other tabs are unchanged.

Third tab selected

Figure 6: Third tab selected

Third tab is selected with Specified Color while other tabs are same.

Explanation of Above Code:

Listing 7: Explanation of code

 <?xml version="1.0" encoding="utf8"  ?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
 
    <! When selected, use grey >
    <item android:drawable="@drawable/tabselectedcolor" android:state_selected="true"/>
    <! When not selected, use white >
    <item android:drawable="@drawable/tabunselcolor"/>

</selector>

Explanation: This tab_selector .xml file is used for selection of background colors of tabs as per current tab is in use. This file has tag which is used for this purpose and tag with in selector is used to behavior of particular item on which this code is used.

<?xml version="1.0" encoding="utf8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >

    <solid android:color="#00dcee" />

</shape>

Explanation: This tabselectedcolor.xml is used to give the background color to that item which is currently selected .

<?xml version="1.0" encoding="utf8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >

    <solid android:color="#ffffff" />

</shape>

Explanation:This tabunselcolor.xml is used to give background color to that item which is not currently selected.

<?xml version="1.0" encoding="utf8"?>
<TabHost xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/host"
    android:layout_width="fillparent"
    android:layout_height="fillparent" >

    <RelativeLayout
        android:layout_width="fillparent"
        android:layout_height="fillparent"
        android:orientation="vertical"
        android:padding="6dp" >

      
  <TabWidget
            android:id="@android:id/tab"
            android:layout_width="fillparent"
            android:layout_height="wrapcontent" />

        <FrameLayout
            android:layout_below="@android:id/tabs"
            android:id="@android:id/tabattribute"
            android:layout_width="fillparent"
            android:layout_height="fillparent"
            android:padding="6dp" />
    </RelativeLayout>

</TabHost>

Explanation: This is the coding of main.xml file. It contains a <TabHost> as root which contains a <RelativeLayout> which having 2 Childs <TabWidget> and <FrameLayout>. <TabHost> will provide the service of hosting tabs as per need and the child <RelativeLayout> will hold the whole UI of screen. <TabWidget> with in RelativeLayout will hold the number of tabs that are defined dynamically and the <FrameLayout> will show the contents of current selected tab.

	intent = new Intent().setClass(this, Activity.class);
		tSpec = tHost.newTabSpec("first").setIndicator("One")
				.setContent(intent);
		tHost.addTab(tSpec);

Explanation: This code in TabCustomization.java will be used as below:

  1. First line will setup the intent to shift when user click on tab.
  2. Second line will do setup the specifications of the tab to be fit.
  3. Third line will put the specified tab on the TabHost which will host the tabs.
tHost.getTabWidget().getChildAt(0).getLayoutParams().height = 40;
		tHost.getTabWidget().getChildAt(0).setBackgroundColor(Color.WHITE);
		tHost.getTabWidget().getChildAt(1).getLayoutParams().height = 40;
		tHost.getTabWidget().getChildAt(1).setBackgroundColor(Color.WHITE);
		tHost.getTabWidget().getChildAt(2).getLayoutParams().height = 40;
		tHost.getTabWidget().getChildAt(2).setBackgroundColor(Color.WHITE);

		tHost.getTabWidget().getChildAt(0)
				.setBackgroundColor(Color.rgb(00, 219, 239));

Explanation: The above code is main code for customization of tabs. This code will get set the height and Background color of tabs as per getChildAt() method used.

@Override
	public void onTabChanged(String tab) {
		if (tabId.equals("first")) {
			tHost.getTabWidget().getChildAt(0)
					.setBackgroundResource(R.drawable.tab_selector);
			tHost.getTabWidget().getChildAt(1).setBackgroundColor(Color.WHITE);
			tHost.getTabWidget().getChildAt(2).setBackgroundColor(Color.WHITE);
		} else if (tabId.equals("second")) {
			tHost.getTabWidget().getChildAt(1)
					.setBackgroundResource(R.drawable.tab_selector);

			tHost.getTabWidget().getChildAt(0).setBackgroundColor(Color.WHITE);
			tHost.getTabWidget().getChildAt(2).setBackgroundColor(Color.WHITE);
		} else if (tabId.equals("third")) {
			tHost.getTabWidget().getChildAt(2)
					.setBackgroundResource(R.drawable.tab_selector);
			tHost.getTabWidget().getChildAt(1).setBackgroundColor(Color.WHITE);
			tHost.getTabWidget().getChildAt(0).setBackgroundColor(Color.WHITE);
		}

	}

}

Explanation: The above code is used as by onTabChangedListener which contains this method named as public string onTabChanged(String tabId). This tabId is used for find out the current selected tab by comparing it with the id given by tHost.newTabSpec() method. In this method background color of current selected tab is changed as per selection means color will be blue if selected else white.

What Is Covered is this article?

  • Customization of Tab Layout dynamically.
  • Introduction to TabHost class methods.
  • Introduction to Intent class.

Also read



Have good knowledge on Java, HTML, CSS and Android platform and is pursuing Masters in Computer Applications.

What did you think of this post?
Services
[Close]
To have full access to this post (or download the associated files) you must have MrBool Credits.

  See the prices for this post in Mr.Bool Credits System below:

Individually – in this case the price for this post is US$ 0,00 (Buy it now)
in this case you will buy only this video by paying the full price with no discount.

Package of 10 credits - in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download few videos. In this plan you will receive a discount of 50% in each video. Subscribe for this package!

Package of 50 credits – in this case the price for this post is US$ 0,00
This subscription is ideal if you want to download several videos. In this plan you will receive a discount of 83% in each video. Subscribe for this package!


> More info about MrBool Credits
[Close]
You must be logged to download.

Click here to login