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 handle Tabs in Android Applications

In this article we will talk about the one of the most essential tools for many GUI layout designs, the Tabbed Navigation. We will also see how the handling tabbed navigation goes from ActionBar.

Tabbed navigation is essential for many GUI layout designs. It makes GUI design efficient, and facilitates user interface. As form Android 3.0, tabbed navigation has been added for tablets and normal phones as well. Handling tabbed navigation goes from ActionBar .

Android 3.x Action Bar

Android 3.x replaces the app’s title bar that was used in earlier Android versions with an action bar at the top of the screen. The app’s icon and name are displayed at the left side.

In addition, the action bar can display the app’s options menu, navigation elements (such as tabbed navigation) and other interactive GUI components. You can also designate menu items as actions that should be placed in the action bar if there is room. To do so, you can set the menu item’s android:showAsAction attribute.

Adjusting the manifest file

The android menu bar can be viewed in line with the tabs bar, or as separate space at the bottom of the screen. In general for Android SDK, you can switch the view to tablet view (horizontal) by clicking (Ctrl + F11). By doing this, the menu bar shall appear on the same level with the tabs of the action bar. However, if there is no room to display all menu items on the same level as the action bar, the application has two options:

Collapse the items and display them as list when clicked.

Collapse the items

Figure 1: Collapse the items

Listing 1: This is achieved by adding the following attribute to the actionmenu.xml layout:

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item 
        android:id="@+id/item1"
         android:title="First Menu Item"
         android:showAsAction="ifRoom|withText">
    
</menu>

Split the menu items at the bottom of the screen when no room. This is also needed in Portrait mode when no room to view the menu in the same tabs level.

Splitting Menu items at bottom of the screen

Figure 2: Splitting Menu items at bottom of the screen

Listing 2: This is achieved by adding the android:uiOptions="splitActionBarWhenNarrow" to the AndroidManifest.xml file as follows:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="mine.testprojects.com"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk android:minSdkVersion="15" />

    <!-- android:uiOptions="splitActionBarWhenNarrow": The following option will allow split Action bar, important for Portrait -->
    <application        
        
        android:icon="@drawable/ic_launcher"       
        android:label="@string/app_name" >
        <activity
            android:uiOptions="splitActionBarWhenNarrow"
            android:name=".TestActionBarActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Adding tabs using ActionBar

Tabs are added to the ActionBar programmatically inside the activity. In fact you need first to get a handle to the Activity action bar, and then you can use it to handle all action bar actions.

Listing 3: Tabs using ActionBar

public class TestActionBarActivity extends Activity 
{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        ActionBar myActionBar = getActionBar();
        
        myActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
        
        Tab tab1 = myActionBar.newTab();
        tab1.setText("First Tab");
        myActionBar.addTab(tab1);

Once action bar handle is obtained, tabs can be added using the “newTab” method, which returns a “Tab” instance. The most important is to set the navigation mode to NAVIGATION_MODE_TABS. Bby doing this, tabs can appear. Using the instance (tab1 in our example) all actions can be done to the new tab, like in our example, using the setText method to add text to the tab. Later we will learn how to style this text, as by default it appears in Capital letters.

Notice that the statement “myActionBar.addTab(tab1);” at the end of the activity onCreate method. Without this call the new tab is not inserted in the app.

ActionBar Styles

The style of your action bar takes the default of the used theme. For example for the “Theme.Holo”, tab text appears as Capitals with blue text.

Listing 4: To fix this issue, first we have to create new Theme style in our Styles.xml file:

<?xml version="1.0" encoding="utf-8"?>
<resources>
	
	<style name="custom_theme" parent="@android:style/Theme.Holo">
	  <item name="android:actionBarTabTextStyle">@style/custom_actionbar_tab_text_style</item> 
	</style>
	<style name="custom_actionbar_tab_text_style">
	        <item name="android:textAllCaps">false</item>
	        
	</style>
    
</resources>

The new theme style is called “custom_theme” in our example, and it inherits from Them.Holo. Since our only aim here is to modify the actionbar style, so the only attribute that we modify than the original parent theme is android:actionBarTabTextStyle. We create a new style custom_actionbar_tab_text_style , and we refer to it when we set the android:actionBarTabTextStyle . As you notice, the attribute android:textAllCaps is set to false for the overridden action bar style, so that text appears as written in the code and not all caps style.

Handling call backs of ActionBar events

There are variety of actions that needs to be handled on tabs. For example you might need to select or un-select a tab programmatically. Also, you might need to perform some actions in your app once a certain tab is selected or un-selected as well. Some time you also need to perform certain specific actions when a tab is re-selected.

Implement a new class, let’s call it “MyTabListener” which must inherit from the TabListener base class which needs to import android.app.ActionBar.TabListener; package.

Listing 5: To do this a set of actions needs to be performed:

 public class MyTabListener implements TabListener
    {
    	private Context context;
    	MyTabListener(Context context)
    	{
    		this.context = context;
    	}

		@Override
		public void onTabReselected(Tab tab, FragmentTransaction ft)
		{
			// TODO Auto-generated method stub
			Toast.makeText(this.context, tab.getText() + " Selected again", Toast.LENGTH_SHORT).show();
			
		}

		@Override
		public void onTabSelected(Tab tab, FragmentTransaction ft)
		{
			// TODO Auto-generated method stub
			//Toast.makeText(this.context, "Tab " + tab.getPosition() + " Selected", Toast.LENGTH_SHORT).show();
			Toast.makeText(this.context, tab.getText() + " Selected", Toast.LENGTH_SHORT).show();
			
			
		}

		// Working if another tab selected after current is selected
		@Override
		public void onTabUnselected(Tab tab, FragmentTransaction ft) 
		{
			// TODO Auto-generated method stub
			Toast.makeText(this.context, tab.getText() + " Unselected", Toast.LENGTH_SHORT).show();
			
		}
    	
    };


Displaying the tab at the bottom

Figure 3: Displaying the tab at the bottom

You notice in the example code that 3 methods are overridden from the base class: onTabSelected(Tab tab, FragmentTransaction ft), onTabUnselected(Tab tab, FragmentTransaction ft), onTabReselected(Tab tab, FragmentTransaction ft). The first one is a call back called when the tab is first selected. The second one is a call back called when the tab is un-selected (or another tab is selected as well), this is equivalent to “when the tab is left”. And the last one is called when the tab is re-selected again. This is equivalent to the user clicks or touches the tab icon while on the same tab. All the three methods takes two main argument: Tab and FragmentTransaction. We focus here on the tab argument which defines which tab instance has been Selected, UnSelected or Re-selected.

In our example, whenever a tab is selected, unselected or re-selected a Toast is shown with short period to indicate the action performed and displays the meant tab text as well. Notice that you can also obtain the tab position by calling tab.getPosition(), which returns the order of the tab in the action bar.

We focused in this example on the main events that needs to be handled in on TabListener classes, but there are many others, like onClickListener, onTouchListnener, onHoverListener,…etc, but they are out of scope of this tutorial.

The second action to be performed is to assign the created class to the tab we want. This is done by calling setTabListener() method on the required tab:

    tab1.setTabListener(new MyTabListener(this));

Notice that, the new class MyTabListener constructor takes the current context as argument to use it to view the Toast messages in our example.

Listing 6: It is also possible to refrain from creating new class and set it to the tab as above. Instead, we can just create it on-spot and set it all in one step:

 tab1.setTabListener(new ActionBar.TabListener()
        {
			
			@Override
			public void onTabUnselected(Tab tab, FragmentTransaction ft) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onTabSelected(Tab tab, FragmentTransaction ft) {
				// TODO Auto-generated method stub
				
			}
			
			@Override
			public void onTabReselected(Tab tab, FragmentTransaction ft) {
				// TODO Auto-generated method stub
				
			}
		});

In the above code, the new class is created inside the setTabListener call in one step, in addition to the implementation of the internal overridden action functions. You can use this style to save creating temporary classes, like MyTabListener in the first example.

ActionBar Menu

As we discussed above, the AcitionBar enables creating menus either as split in the bottom of the app, or in line with the tabs. In fact it is necessary to inflate the action menu layout using the traditional LayoutInflater class.

Listing 7: The layout that will be inflated is the actionmenu.xml layout defined above.

  @Override
    public boolean onCreateOptionsMenu(Menu menu) 
    {
    	super.onCreateOptionsMenu(menu);
    	getMenuInflater().inflate(R.menu.actionmenu, menu);
    	return true;
    }

The code demonstrated here presents how to override the onCreateOptionsMenu method of the main Activity class. The super constructor method is first called and then our actionmenu.xml layout is inflated using the activity layout inflater. To obtain an instance of the Activity layout inflater we can call getMenuInflater()defined for the activity class. Using the returned instance the layout of the action menu can be inflated.

Notice that, if android:showAsAction="ifRoom|withText" is not set in the menu layout xml file, the menu shall be inflated only as ordinary menu with the clicking of the menu key on the phone, but not as split or in-line action bar menu as presented before.

Conclusion

In this tutorial we learnt how to create a tabbed navigation Android Application. We learnt how to handle tabs in the Android 3.x action bar, style them and handle their call backs as well. We dealt with the action bar menus. We also learnt how to deal with space and area issues by splitting the action bar menu or use the overflow menu.



I am a software developer from India with hands on experience on java, html for over 5 years.

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