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

Creating Tabs in Android

In this article we will see the process to create tabs in an Android Application. This is the easier way to navigate through the different parts of an app quickly.

Implementing tabs enhances an app’s UI and provides an easy way to navigate through the different parts of an app quickly. Consider a scenario where you want to develop a contacts manager app, which consists of four activities: adding a contact, deleting a contact, searching a contact, and speed dial. Such an app can be easily developed by using tabs. Tabs will help you to navigate easily to the different parts of an app. The following figure depicts a tabbed app.

An Example of a
Tabbed App

Figure 1: An Example of a Tabbed App

In order, to implement tabs in an Android app, the following components are required:

  • Tab host: It is the main container for tab buttons and tab content.
  • Tab widget: It consists of the row of buttons, which may contain icons and/or text labels.
  • Frame layout: It is the container for the tab content. The following figure displays the preceding components.

The Various
Components for Tabs

Figure 2: The Various Components for Tabs

Creating a Tabbed UI

To create a tabbed UI, you need to use the <TabHost>, <TabWidget>, and <FrameLayout> elements, where the <TabHost> element acts as a container for the <TabWidget> and <FrameLayout> elements. A tab host can be implemented in one of the following two ways, depending on your app requirements:

  • By navigating through multiple views within one activity.
  • By navigating through multiple activities using intents. The following markup explains how to create an XML layout for tabs:

In the preceding markup, the <FrameLayout> element consists of two linear layouts with the ids, tab1 and tab2. These linear layouts correspond to the tab1.xml and tab2.xml files respectively, which consist of the content to be displayed when the corresponding tab gets selected. The following markup shows an example of the content of the tab1.xml and tab2.xml files:

Implementing Tabs

After creating the layout for tabs, you will need to provide the functionality for the tab buttons. To implement tabs, you will need to use the TabHost class available in the android.widget package. It holds a set of tab labels to select a specific tab and a FrameLayout object that displays the content of the tab. The TabHost class is used to control the individual tab elements. The following table displays some methods defined in the TabHostclass.

Method

Parameters

Description

addTab(TabHost.TabSpec tabSpec)

tabSpec: Specifies the way to create the tab indicator and content.

Adds a tab with the specific tab specification.

clearAllTabs()


Removes all tabs from the tab widget that is associate with the tab host.

getTabContentView()


Retrieves FrameLayout that holds the tab content.

newTabSpec(String tag)

tag: Refers to the tag text of the tab.

Retrieves a new tab specification associated with the tab host.

setup()


Is called before adding tabs after the tab host been loaded by using the findViewById() method.

Table 1: The Methods of the TabHost Class

A tab consists of the following components:

  • Tab indicator: A label or a label with an icon. The TabHost.TabSpec class is used to set the tab indicator. The TabHost.TabSpec class also provides the TabSpec.setIndicator() method that allows you to set the title for the tab.
  • Tab content: The content to be displayed for the tab. You can specify the content for each tab by using the TabSpec.setContent() method.
  • Tag: The text displayed for the tab. To implement tabs in your activity, you need to extend the activity from the TabActivity class available in the android.app package. The following code snippet shows how to implement tabs by using the TabHost and TabSpec classes:
public class MainActivity extends TabActivity { 
// Declaring TabHost and TabSpec objects .
     TabHost tabHost; 
     TabSpec spec1; 
     TabSpec spec2; 
     @Override public void onCreate(Bundle savedInstanceState) { 
          super.onCreate(savedInstanceState); 
          setContentView (R.layout.activity_main); 
          // Initializing the Tab host. 
          tabHost=(TabHost)findViewById (android.R.id.tabhost); 
          tabHost.setup(); 
          // Creating tab1. 
          spec1=tabHost.newTabSpec(“Tab 1”); 
          // Using the tab1.xml file for tab1 content .
          spec1.setContent(R.id.tab1); 
          // Setting a label and an icon for tab1.
          spec1.setIndicator(“E-MAIL”, getResources().getDrawable (R.drawable.ic_launcher)); 
          // Calling ActivityOne through intent .
          Intent in1=new Intent(this, ActivityOne.class); 
          spec1.setContent(in1); 
          // Creating tab2.
          spec2=tabHost.newTabSpec(“Tab 2”); 
          spec2.setContent(R.id.tab2); 
          // Using the tab2.xml file for tab2 content.
          spec2.setContent(R.id.tab2); 
          // Setting a label and an icon for tab2.
          spec2.setIndicator (“MESSAGES”,getResources().getDrawable (R.drawable.ic_launcher)); 
          // Calling ActivityTwo through intent.
          Intent in2=new Intent(this, ActivityTwo.class); 
          spec2.setContent(in2); 
          // Adding tab1 and tab2 to the TabHost.
          tabHost.addTab(spec1); 
          tabHost.addTab(spec2); 
     } 
                                                                                       
}

The following figure displays the output of the preceding code.

A Tabbed Layout

Figure 3: A Tabbed Layout

Applying Styles and Themes

A style is a collection of attributes used to specify the look and format for a view or a window. We can customize the various properties of an app by using styles, such as height, padding, font color, font size, and background color. Styles on the Android apps are similar to the cascading style sheets in Web pages, allowing us to separate the design from the content. A theme is a style applied to an entire app or activity. When a style is applied as a theme, every view in the activity or app will implement each style property that it supports. For example, you can apply the font style as a theme for an activity, and then all text views inside that activity will display text in that font style.

Creating Styles

To apply styles in an Android app, you need to define an XML file. This file must be saved in the res/values folder of the project in which you want to implement the styles. You need to implement the following elements for using styles in your activity:

  • <resources>: Declares the root node in the XML file.
  • <style>: Declares a style. It must implement the name attribute that uniquely identifies each style.
  • <item>: Declares a property of the style. It must implement the name attribute that declares the style property and its corresponding value.

The value can be a keyword string, a hex color, a reference to another resource type, or other value, depending on the property of the style. The following markup explains the way to create a file with a single style:

<?xml version=“1.0” encoding=“utf-8”?>
                    
  <resources> 
   
       <style name=“Mystyle” parent=“@android:style/ TextAppearance.Medium”> 
       <!--Items within a single style element --> 
       <!--Specifying the color of the text --> 
       <item name=“android:textColor”>#00FF00</ item> 
       <!-- Specifying the type of the text--> 
       <item name=“android:typeface”>serif</ item> 
       <!--Specifying the style for the text --> 
       <item name=“android:textStyle”>bold</ item> 
       <!--Specifying the size for the text--> 
       <item name=“android:textSize”>20dip</ item> 
       </style> 
  </resources> 
  

In the preceding markup, the parent attribute declared within the element is optional. It is used to specify the resource ID of another style from which this style should inherit some properties. Though, you can later override the inherited style properties. In addition, at the time of compilation, every element within the <resources> element will get converted into an instance of the app resource and can be referenced later in either the XML file or the manifest file.

Inheriting Styles

The parent attribute of <style> the element allows you to inherit properties from an existing style. You can later define or change the properties that you want to modify or add. For example, you can inherit the default text appearance, and then modify it as shown in the following markup:

<!--Here parent attribute is an inbuilt style which is implemented in a custom style declared in the name attribute. The custom style is modifying the color to olive --> 
<style name=“Mystyle” parent=“@android:style/ TextAppearance”> 
   <!--Changing the text color to olive --> 
   <item name=“android:textColor”> #909000 </item> 
                           
</style>

In order to inherit your own style, the parent attribute is not required. You can prefix the name of the inherited custom style to the name of the created style, separated by using a period. The following markup shows how to inherit your own style:

<!-The parent style is Mystyle and the new style is Blue --!> 
   <style name=“Mystyle.Blue ” > 
<!--Changing the color from olive to blue --> 
      <item name=“android:textColor”>#0000FF</ item> 
                           
   </style>

This new style will implement all the properties defined in the Mystyle style, but it will override the color property and change it to the color specified in this style. This new style can be referenced as @style/Mystyle.Blue. You can implement inheritance of attributes by chaining the name with periods, as shown in the following code snippet:

<style name=“Mystyle.Blue.Italic” > 
<!-Changing the text style to italic--> 
   <item name=“android:textStyle”>italic</item> 
                         
</style>

The preceding markup inherits from both, the Mystyle styleand the Mystyle.Blue style.

Using Styles

After creating styles, the next step is to use them for your views. You can use styles in the following two ways:

  • You can set the style for an individual element.
  • You can apply the style as a theme to the entire activity or app.

To set a style for an element, you can set the style attribute of widgets in the XML file, as shown in the following markup:

<!--Style.xml-->
                   <?xml version=“1.0” encoding=“utf-8”?> 
       <resources> 
            <style name=“MyStyle”> 
            <!--Setting text size--> 
            <item name=“android:textSize”>20sp</ item> 
            <!--Setting the type face for the text --> 
            <item name=“android:typeface”>serif</ item> 
            <!--Setting the style for the text --> 
            <item name=“android:textStyle”>italic</item> 
            <!--Setting the color--> 
            <item name=“android:textColor”>#FFFFFF </item> 
            </style> 
       </resources>
   
  <!--main.xml--> 
  <?xml version=“1.0” encoding=“utf-8”?> 
  <LinearLayout xmlns:android=“http:// schemas.android.com/apk/res/android” android:orientation=“vertical” android:layout_width=“fill_parent” android:layout_height=“fill_parent” > 
   
  <!--Implementing the style created in Style.xml for a single view--> 
   
  <TextView style=“@style/MyStyle” android:text=“@string/Music” android:id=“@+id/textView2” android:layout_width=“wrap_content” android:layout_height=“wrap_content”>
       
  </TextView> 
       <LinearLayout android:layout_width=“match_parent” android:layout_height=“wrap_content” android:id=“@+id/linearLayout1” android:orientation=“vertical”> 
            <RadioButton android:text=“@string/ON” android:id=“@+id/radioButton1” android:layout_width=“wrap_content” android:layout_height=“wrap_content”>
                 
            </RadioButton> 
            
            <RadioButton android:text=“@string/OFF” android:id=“@+id/radioButton2” android:layout_width=“wrap_content” android:layout_height=“wrap_content”>
                 
            </RadioButton> 
            
            <Button android:id=“@+id/button1” android:layout_height=“wrap_content” android:text=“Save” android:layout_width=“wrap_content”>
                 
            </Button> 
       </LinearLayout> 
  </LinearLayout> 
  

The following figure displays the output of the preceding markup.

Setting a Style for
the Text View

Figure 4: Setting a Style for the Text View.

In the preceding figure, observe that the TextView widget for which the style=“@style/MyStyle”attribute was used, displays text in the custom style. To apply the style as a theme to the entire activity or app, you can add the android:theme attribute to the <activity>or <application>element in the manifest file. The following markup shows how to implement styles for an activity:

<activity android:name=“.CustomStylesActivity” android:label=“@string/app_name” android:theme=“@style/MyStyle”>

If you want a theme applied to the entire app, you need to add the android:theme attribute to the tag instead.

Note: All view objects don’t accept all style attributes, and therefore, you need to refer to the specific view class for supported style properties. If you apply a style to a view that doesn’t support all properties defined in the style, it will apply only those properties that are supported by the view.

Some style properties are not supported by view elements. These properties are only applied as themes for the entire window. These attributes usually begin with the word, window, such as windowNoTitle and windowBackground.

Creating Custom Views

The ability to extend the existing views, create composite widgets, and create unique new controls allows you to create attractive UIs optimized for your particular workflow. Android lets you subclass the existing widget toolbox and implement your own views, giving you total freedom to tailor the UI to maximize the user experience. In Android, you can easily create fully-customized controls that can look and behave in any way you like. To create a customized control, you can extend the View class to create a new component and supply a constructor that can use attributes and parameters declared in the XML file, as shown in the following code snippet:

public class MycustomButton extends View { 
    public MycustomButton(Context context) { 
     super(context); 
 
    // TODO Auto-generated constructor stub .
    
     }
                                 
 }

While creating custom controls, you can declare your own attributes. You can also create your own event listeners, property accessors, and modifiers, and override the onMeasure()or onDraw()method. The onDraw() method provides a canvas. This canvas allows you to implement 2D graphics, styled text, other standard/custom components, and so on. The following code snippet shows the skeleton of the onDraw() method:

@Override protected void onDraw(Canvas canvas) { // code goes here }

Android provides the various tools that help you to draw your design on the canvas by using the various paint objects. The android.graphics.Canvas class provides you with the helper methods to draw primitive 2D objects, such as circles, lines, rectangles, text, and drawables (images). This class also provides support for transformations, allowing you to rotate, translate/move, and scale/resize the canvas while you draw on it. If you don’t require the control that always occupies 100x100 pixels, you need to override the onMeasure()method. The onMeasure()method is just a contract between your component and its container. It is used to report the measurement of the contained parts. This method takes the following two parameters:

  • widthMeasureSpec: It refers to the horizontal space requirements as imposed by the parent.
  • heightMeasureSpec: It refers to the vertical space requirements as imposed by the parent. The following code snippet shows the skeleton of the onMeasure()method:
@Override protected void onMeasure(int
widthMeasureSpec, int heightMeasureSpec) { //code
} 

The preceding method measures the view and its content to determine the measured width and measured height. This method should be overridden by subclasses to provide an accurate and efficient measurement of their contents. In order to use a custom view, you need to specify the package name with the class name, as shown in the following code snippet:

<com.android.Custom.MyCustomView id=“@ +id/note” />

In the preceding code snippet, the package name is referred along with the class name. If your app consists of inner classes, you can implement these in the XML file of the inner class, as shown in the following code snippet:

<view class=“com.android.Custom.InnerClass $MyCustomView ” id=“@+id/note” android:layout_width=“fill_parent” android:layout_height=“fill_parent” android:background=“@android:drawable/empty” android:padding=“10dip” android:scrollbars=“vertical” android:fadingEdge=“vertical” />

In the preceding code snippet, the inner class defined is referenced by using the InnerClass$MyCustomView notation, which is a standard way to refer to the inner classes in Java. You can also make your widgets interactive, if the customized controls respond to the user events, such as a key press or click. Android exposes the following virtual event handlers that can be used to react to the user input:

  • onKeyDown: Invoked when any device key is pressed. It includes the device’s keypad, camera buttons, dialing pad, back buttons, and hang-up buttons.
  • onKeyUp: Invoked when the user releases a pressed key.
  • onTrackballEvent: Invoked when the trackball of the device is used.
  • onTouchEvent: Invoked when the user does a tap or a click on the touch screen of the device.

This is all for today’s article, I hope you're enjoying my tutorials in the MrBool website, please give your feedback below leaving a comment to my article.

See you next time.



Certified Trainer for Windows 8 Mobile App Development, IBM CE Project Trainer With IBM DB2, RAD, RSA, Certified Trainer for ZEND (PHP), Certified PHP and MySql trainer, Certified trainer of Diploma in Oracle 10g (DBA) as per Orac...

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