Click here to Skip to main content
Click here to Skip to main content

Article 4 - Android UI Layout and Controls

, 15 Aug 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
This article explains various Android UI Layouts and the components that one can use in designing the screens. Also we have some tips and best practices that one can follow in improving the application performance.

Introduction

In this article we will mainly see the various Android Layouts, it's usages with examples. Also this article deep dives into some of the most commonly used Andorid controls in day to day developement. You can navigate through the topics from the below links or go sequentially from top to bottom.

Note - The Android UI components make use of textSize with units 'dp' , 'sp' etc. Please have a look into the others section, tips and best practices to know more about these units.

Andorid Layout Types


Android UI Controls


Others

Tips and Best Practices

 

Background

Good understanding and knowledge of Java programming is highly recommended. 

Please find the below link for "Introduction to Android"


http://www.codeproject.com/Articles/802449/Article-Introduction-to-Android
 

Please refer the below mentioned article to setup your development environment.

http://www.codeproject.com/Articles/803609/Article-Setting-Up-Your-Android-Development-Enviro

 

Overview of Different Android UI Layout Types

Let us see an overview of different android UI layouts. 

Android is very flexible with the view layouts. You have two options to declare a layout. Either you can go with declaring the layout in activity layout xml file or you can do everything within your activity class file. The most preferred way of managing the application layout is by declaring them in xml file as your view will always be decoupled and it’s very easy to manage your UI elements. One benefit that you would get by declaring the view elements in xml file is, say you wish to modify some of your view elements in such cases you don’t have to recompile your application to see the changes when you are developing the application. Hence any changes to the layout xml file will have an immediate effect on the preview. Before we dig into understanding different layouts, lets us first try to understand what view, view group is. 

View – A View is the basic building block of a user interface. It is mainly responsible for drawing and event handling. A view is nothing but an object it’s created from a view class which occupies a rectangular area in a screen. 

ViewGroup – A ViewGroup is a sub class of View. It mainly provides an invisible container, which by itself holds other views or view groups.

The layouts are subclasses of a view group class and they are used to define the structure of an android user interface. 

Here’s the pictorial representation of different layouts with view and view group.

Layouts

Linear Layout

A linear layout is one of the simplest and commonly used layouts among others. It is a class which extends view group. It is mainly used to display all children elements in a linear fashion either fully horizontally (in a single row) or vertically (in a single column). If you are a windows phone programmer, you can related the same to a StackPanel, using which one can either arrange all items either “Horizontally” or “Vertically”. One can set the direction of the linear layout by setting the LinearLayout.Orientation. 

Here’s a code snippet were we are arranging all child elements vertically in a linear layout. 

1. We are adding a LinearLayout. Then set the width, height with orientation set to ‘Vertical’ so that all elements within the linear layout will be arranged vertically.

2. Add a TextView view element to display the welcome title and others.

Coming next, we will see in details about the linear layout properties.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools=&rdquo;http://schemas.android.com/tools&rdquo;
       android:layout_width="match_parent"
       android:layout_height="match_parent"
       android:orientation="vertical"
       tools:context=".LinearLayout">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Welcome to CodeProject"
            android:textSize="30px"
            android:paddingTop="10px"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Home"
            android:textSize="30px"
            android:paddingTop="50px"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Articles"
            android:textSize="20px"
            android:paddingTop="50px"/>
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Quick Answers"
            android:textSize="20px"
            android:paddingTop="50px"/>
</LinearLayout>

Here’s how it looks like in design mode.

LinearLayout1

Now let us see how to define a linear layout programmatically within the activity java class file. The following things need to be kept in mind.

1.    Linear layout specific properties which are applied to LinearLayout can be accessed with in the code using view.ViewGroup.LayoutParams.

2.    The child level layout specific properties can be accessed using LinearLayout.LayoutParams class. 

3.    If you look into the activity class file, you will see the below code onCreate override. First you have to build the linear layout with all its children’s and then make a call to setContentView with the linear layout xml. 

setContentView(R.layout.activity_linear_layout);

Here’s the code snippet to create a simple linear layout.  You can notice below, the entire layout is being programmatically created within onCreate() method by creating an instance of TextView and LinearLayout. The orientation of a linear layout is being set to vertical and also the text gravity is set to CENTER so that the text gets displayed in center of the screen.

The setContentView is passed with linear layout instance so that will set the content view of our activity. Also notice the background color of the linear layout is being set based on the color defined in the resource file under values/Colors.xml. It’s a new resource file that is created to define all the colors so that we can make use of the same in our application by accessing the same through R file.

@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        TextView textView = new TextView(this);
        textView.setText("Welcome to CodeProject");
        textView.setTextColor(parseColor("white"));
        textView.setTextSize(30);
        textView.setGravity(Gravity.CENTER);
        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        linearLayout.setLayoutParams(new ViewGroup.LayoutParams(WRAP_CONTENT, WRAP_CONTENT));
        linearLayout.setGravity(Gravity.CENTER);
        linearLayout.addView(textView);
        Resources res = getResources();
        int color = res.getColor(R.color.orange);
        linearLayout.setBackgroundColor(color); 
        setContentView(linearLayout);
}

Here's the emulator ouput of the LinerarLayout code within the activity class file.

LinearLayout2

Let us now see some of the interesting LinearLayout properties. Most of the properties are self-explanatory.

  • android:id  - Which is used to uniquely identify the layout.
  • android:layout_width - Used to set the width of the layout.
  • android:layout_height  - Used to set the height of the layout
  • android:layout_gravity - A gravity specifies how the child Views are positioned. You can position the view elements either left, right, top, bottom. If you take a look into our example code the gravity is explicitly set to center using setGravity method.
  • android:layout_weight  - Used to specify the extra space in the layout that should be allocated to the View element. You can either set this property with a decimal value which totals up to 1 or you can set this value with a number. The space will be filled proportionally based on the number you set.
  • android:layout_x    - Used to specify the x-coordinate of the layout.
  • android:layout_y    - Used to specify the y-coordinate of the layout.
  • android:layout_width    - Used to specify the width of the layout.

Margin Properties of a LinearLayout

You can set the top, left, right, bottom margin of a linear layout. When the margins are applied, it always leaves space on the outside of the view element.

  • android:layout_marginTop -  Used to set the top margin of the layout. If set, you will see some space at the top side of the layout.
  • android:layout_marginBottom – Used to set the bottom margin of the layout.
  • android:layout_marginLeft – Used to set the left side margin of the layout. When set, it leaves space towards the left side of the layout.
  • android:layout_marginRight – Used to set the right side margin of the layout.


Padding Properties of LinearLayout

Padding are inner margins. When you apply padding, it is always applicable to the space inside the view element.

  • android:paddingLeft    - Used to specify the left padding for the layout.
  • android:paddingRight    - Used to specify the right padding for the layout.
  • android:paddingTop    - Used to specify the top padding for the layout.
  • android:paddingBottom     - Used to specify the bottom padding for the layout.


Relative Layout

A relative layout (also a flexible layout) is a class which extends ViewGroup. It’s used to display the child view in relative positions. The relative layouts by it-self are very powerful. You can make use of one Relative Layout in your layout file and position all the view elements as you wish; which means you don’t have to go with multiple ViewGroups such as LinearLayout. This in-turn flattens the layout hierarchy and improves the performance.

Here's are some of the important relative layout properties.

  • android:layout_alignParentTop - When set to "true", it makes the top edge of the view to match the top edge of the parent.
  • android:layout_centerVertical - When set to true, it centers the child vertically within its parent.
  • android:layout_below - Used to position the top edge of the view below the specified view with an ID.
  • android:layout_toRightOf - Used to position the left edge of this view to the right of the specified view with an ID.

Below we look into the sample that we are coding for RelativeLayout.  Here’s the snapshot of our RelativeLayout demo app. Note – For now we just code everything in layout (xml) file.

RelativeLayout

1.    First let us put make use of RelativeLayout with width and height set to ‘fill_parent’ and background color as ‘Orange’. Note – For convenience we can maintain all colors say in values/colors.xml and use the same across the application.

2.    We will use a TextView, with the text set to ‘Welcome to CodeProject’ , gravity as center and with other relative layout properties set as below.

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Welcome to CodeProject"
        android:id="@+id/textViewWelcome"
        android:layout_gravity="center"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="30px"
        android:textColor="#000000"/>

3.    Next, we will make use of two TextView’s (which is nothing but Labels in Windows Programming). One we set with text as ‘Email’ and the other with ‘Password’. Notice the Email TextView is set with layout_below as under txtViewWelcome with layout_alignPatentRight as ‘false’, margin top as ‘10dp’. Were as the password TextView is set with the layout_below as under Email, with margin top set to ‘10dp’. ‘dp’ is nothing but density-independent pixels.

<TextView
        android:layout_width="200dp"
        android:layout_height="40dp"
        android:text="Email"
        android:id="@+id/textView2"
        android:layout_below="@+id/textViewWelcome"
        android:layout_alignParentRight="false"
        android:textSize="15dp"
        android:layout_marginTop="10dp"
        android:textColor="#000000"/>
<TextView
        android:layout_width="200dp"
        android:layout_height="40dp"
        android:text="Password"
        android:id="@+id/txtViewPassword"
        android:layout_below="@+id/email"
        android:layout_marginTop="10dp"
        android:textSize="15dp"
        android:textColor="#000000"/>

4.    Next we will make use of two EditText one for email and the other for password and set the respective layout properties to align toward right with layout_below.

<EditText
        android:layout_width="200dp"
        android:layout_height="40dp"
        android:hint="E-mail"
        android:id="@+id/email"
        android:layout_below="@+id/textViewWelcome"
        android:layout_alignParentRight="true"
        android:textSize="15dp"
        android:textColor="#000000"/>
<EditText
        android:layout_width="200dp"
        android:layout_height="40dp"
        android:inputType="textPassword"
        android:id="@+id/Password"
        android:hint="Password"
        android:layout_below="@+id/email"
        android:layout_alignParentRight="true"
        android:textSize="15dp"
        android:textColor="#000000"/>

5.    In the end, we will make use of three Buttons for Register, Login and Forget password. 

​<Button
        android:layout_width="170dp"
        android:layout_height="40dp"
        android:text="Login"
        android:id="@+id/login"
        android:textSize="13dp"
        android:textColor="#000000"
        android:layout_alignTop="@+id/RegisterButton"
        android:layout_alignParentRight="true"/>
<Button
        android:layout_width="220dp"
        android:layout_height="40dp"
        android:text="Register"
        android:id="@+id/RegisterButton"
        android:layout_below="@+id/Password"
        android:textSize="13dp"
        android:textColor="#000000"
        android:layout_toLeftOf="@+id/login"/>
<Button
        android:layout_width="wrap_content"
        android:layout_height="40dp"
        android:text="Forgot Password"
        android:id="@+id/PasswordReset"
        android:layout_below="@+id/login"
        android:layout_alignParentRight="true"
        android:layout_alignParentLeft="true"
        android:textSize="13dp"
        android:textColor="#000000"/>


Table Layout 

The TableLayout is a ViewGroup which can be used to arrange elements in rows and columns. The best analogy for a TableLayout is the HTML <table> tag, were you can make use of it to position the HTML elements in a table row and column. Like HTML table, the TableLayout has a TableRow, which are children’s of a TableLayout. However unlike html table <td>, the android TableLayout does not have a cell. Instead you can zero or more objects with in the TableRow.

Let us see with an example of how we can define a TableLayout with TableRow and add some view elements inside it. In this example, we will also be using LinearLayout.

1.    Start a New project by selecting a blank layout.

2.    Let us first define a TableLayout and set some basic properties like height, width.  We are going to set the stretchColumns = 1. The first column to be stretched. 

<TableLayout xmlns:android=&rdquo;http://schemas.android.com/apk/res/android&rdquo;
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:stretchColumns="1" /> 

3.    Now let us create a TableRow with ImageView for displaying logo and TextViews for displaying text (“Code”, “Project” and "for those who code"). Below is the code snippet for the same. Note – The logo is positioned with column = 0 and LinearLayout with column = 1.

<TableRow
        android:layout_width="fill_parent"
        android:layout_height="fill_parent">

        <ImageView
            android:layout_width="wrap_content"
            android:layout_height="fill_parent"
            android:id="@+id/imageView"
            android:layout_column="0"
            android:src="@drawable/codeprojectlogo"
            android:baselineAlignBottom="false" />

        <LinearLayout
            android:orientation="vertical"
            android:layout_width="fill_parent"
            android:layout_height="fill_parent"
            android:layout_column="1">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="30dp"
                android:text="CODE"
                android:id="@+id/txtCode"
                android:textSize="20dp"
                android:background="@color/orange"
                android:paddingLeft="10dp"
                android:textColor="#ffffff"/>
            <TextView
                android:layout_width="match_parent"
                android:layout_height="30dp"
                android:text="PROJECT"
                android:id="@+id/textProject"
                android:textSize="20dp"
                android:paddingLeft="10dp"
                android:background="@color/orange"
                android:textColor="#ffffff" />
            <TextView
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:text="For those who code"
                android:id="@+id/textForThoseWhoCode"
                android:textSize="20dp"
                android:paddingLeft="10dp"
                android:background="@color/orange"
                android:textColor="#000000" />
        </LinearLayout>

</TableRow> 

4.    The sample application contains four buttons. Let us try to add a new TableRow and then within it, we will add a Button view element with a layout column = 0 and layout span = 2 so that the element gets displayed in a full row. Below is the code snippet for the same.

<TableRow
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:paddingTop="20dp">
        <Button
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Home"
            android:id="@+id/btnHome"
            android:background="@color/orange"
            android:textColor="#ffffff"
            android:layout_column="0"
            android:layout_span="2" />
</TableRow>

Here’s the pictorial representation of how the layout code maps to the design. 

TableLayoutCode

Here’s how our TableLayout based Activity layout looks like.

TableLayout

Absolute Layout 

The absolute layout is defined with AbsoluteLayout element. It lets you to specify the exact location where you want to position the view elements. The positions are based on the x and y co-ordinates. Please note that AbsoluteLayout is deprecated but it’s still supported and may be it won’t be available in future android API releases.

Let us code a small app to understand how the absolute layout can be used with in an activity layout. 

1.    Create a new project with blank layout.

2.    Let us remove the default RelativeLayout view element from our activity and make use of AbsoluteLayout as below. You can notice below, we are setting the absolute layout background as orange which is coming from a resource file colors.xml under values folder. You have to create one; it does not come by default.

<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/orange">
</AbsoluteLayout>

3.    Now let us create a simple TextView with text as ‘Welcome to CodeProject’ and position the same with layout_x and layout_y as shown below. 

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:text="Welcome to CodeProject"
        android:id="@+id/textWelcomeText"
        android:layout_x="32dp"
        android:layout_y="40dp"
        android:textStyle="bold"
        android:textSize="30dp" /> 

4.    Now let us try to create few buttons and positon the same by setting the x and y co-ordinate of the view.

<Button
        android:layout_width="283dp"
        android:layout_height="wrap_content"
        android:text="Home"
        android:id="@+id/btnHome"
        android:layout_x="48dp"
        android:layout_y="148dp" />
    <Button
        android:layout_width="283dp"
        android:layout_height="wrap_content"
        android:text="Articles"
        android:id="@+id/btnArticles"
        android:layout_x="50dp"
        android:layout_y="247dp" />
    <Button
        android:layout_width="283dp"
        android:layout_height="wrap_content"
        android:text="Question Answers"
        android:id="@+id/btnQuestionAnswers"
        android:layout_x="50dp"
        android:layout_y="351dp" />

Here’s the pictorial representation of the code and the corresponding design. 

AbsoluteLayoutCode


Frame Layout 

The FrameLayout is a ViewGroup which is used to display a single item within a block of area. Just as an analogy, you can think of it as a HTML div, where you can organize some of the HTML elements within it. You can add one or more view elements within a FrameLayout and display them by setting the gravity to each view element. 
Let us now try to understand the FrameLayout with a simple example. Here we will make use of a FrameLayout with an ImageView to display CodeProject Logo and three TextViews to display (Code, Project and ‘for those who code’)

1.    Create a new project with blank layout.

2.    Let us remove the default layout code and add a new FrameLayout as shown below.

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/orange">
</ FrameLayout>

3.    Add ImageView to display CodeProject Logo.

<ImageView
        android:src="@drawable/codeprojectlogo"
        android:scaleType="fitCenter"
        android:layout_height="250px"
        android:layout_width="250px"/>

4.    Add text boxes to display texts “Code”, “Project” and “for those who code”. Let us see a sample code for a single TextView which displays “Code” text.  Note – We will be positioning the text using gravity set to ‘right’ and setting paddingTop and paddingRight.

<TextView
        android:text="CODE"
        android:textSize="50px"
        android:textStyle="bold"
        android:layout_height="128dp"
        android:layout_width="match_parent"
        android:textColor="@color/white"
        android:paddingTop="20dp"
        android:paddingRight="180dp"
        android:gravity="right"/> 

Here’s the pictorial representation of the usage of the FrameLayout code and the corresponding design.

FrameLayoutCode

List View

ListView is a ViewGroup, unlike layouts which directly extends from ViewGroup class; the ListView directly extends from AbsListView.  You can use a ListView to show a vertically scrolling list of items in an activity. An adapter is what it’s used to display the list view items. The adapter basically acts as a bridge between the data source and the ListView instance. 

Let us take a look into an example to understand how a ListView can be used and populated with some items. 

1.    Create a new project with blank layout.

2.    Let us remove the default layout code and add a new LinearLayout with orientation set to vertical. Then add a ListView element with in it.

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
       android:layout_width="fill_parent"
       android:layout_height="fill_parent">
    <ListView android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:id="@+id/listView">       
    </ListView>
</LinearLayout>  

3.    We will be creating a layout resource file named ‘listviewitem.xml’ with a TextView, under layout folder. Which we will be using it to display the ListView items using TextView. Here’s the code snippet.

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/rowTextView"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="10dp"
    android:textSize="16sp" >
</TextView>  

4.    We will be writing a code within the onCreate override of our ListViewActivity java class file. Here’s the code snippet for the same.

1)    Let us first get a reference to the list view by using findViewById.

2)    Next, let us build a list of strings. We will be adding all the days from Monday thru Sunday.

3)    Next we create an adapter instance by making use of an ArrayAdapter with a view and a collection to display all the list view items.

4)    At last we will be making a call to listview setAdapter method with the adapter instance that we had created in step 3. 

@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.listviewactivity);
        ListView listView = (ListView) findViewById( R.id.listView );
        List<String> days = new ArrayList<String>();
        days.add("Monday");
        days.add("Tuesday");
        days.add("Wednesday");
        days.add("Thursday");
        days.add("Friday");
        days.add("Saturday");
        days.add("Sunday");
        ArrayAdapter listAdapter = new ArrayAdapter<String>(this, R.layout.listviewitem, days);
        listView.setAdapter(listAdapter);
}

Here’s the emulator output of our ListView sample app.

ListView

Grid View 

GridView is a ViewGroup which extends from AbsListView like ListView. You can make use of a grid view to display items in rows and columns. 

Here’s the list of attributes that one can set for a GridView element.

android:columnWidth - Used to specify the fixed width for each column. 
android:gravity    - Used to specify the gravity. You can set the gravity with top, bottom, left, right, center etc. When specified, it’s applicable for each cell within a gridview.
android:horizontalSpacing - Used to specify the default horizontal spacing between columns. 
android:numColumns -  Used to specify how many columns to show. 
android:stretchMode -    Used to specify how the columns should within the cell. You can set with the following values.

•    none – When set the stretching will be disabled.

•    spacingWidth – Based on the specified width, the spacing between each column is stretched.

•    columnWidth – Based on the specified column width, each column is stretched equally.

•    spacingWidthUniform - The spacing between each column is uniformly stretched.
android:verticalSpacing    - Used to specify the default vertical spacing between rows. 

Let us see with an example to understand the usage of GridView. In this example, we will be displaying static images in GridView.

1.    Create a new project with blank layout.

2.    Download or replace the images from res/drawable-hdpi folder. We will be using those images and display the same in GridView.

3.    Let us remove the default layout code and add a new GridView element as shown below. Note we will set the number of columns to display as ‘2’, gravity as center. Also we will set the horizontal and vertical spacing, column width etc.

<GridView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/gridView1"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:columnWidth="90dp"
    android:numColumns="2"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:stretchMode="columnWidth"
    android:gravity="center"
/>

4.    Now let us build a custom image display adapter by extending from BaseAdapter. Before we start writing some code, below are the packages that we need to import. 

import android.content.Context;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;

Here’s the code snippet of our custom image display adapter. We need to pass in the context instance and the list of image Ids so that we can create an ImageView and set the image resource based on the list of images. 

public class ImageDispalyAdapter extends BaseAdapter
{
    protected Context context;
    protected Integer[] imagesIds;
    public ImageDispalyAdapter(Context c, Integer[] imagesIds)
    {
        context = c;
        this.imagesIds = imagesIds;
    }
    public int getCount() {
        return imagesIds.length;
    }
    public Object getItem(int position) {
        return position;
    }
    public long getItemId(int position) {
        return position;
    }
    public View getView(int position, View convertView, ViewGroup parent)
    {
        ImageView imageView;
        if (convertView == null) {
            imageView = new ImageView(context);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            imageView.setPadding(2, 2, 2, 2);
        } else {
            imageView = (ImageView) convertView;
        }
        imageView.setImageResource(imagesIds[position]);
        return imageView;
    }
}

5.    Now let us start coding the activity class file in setting the adapter to display images. Here’s the onCreate override code. You can see below, we need to get a reference to a gridview defined in activity layout and then set the gridview adapter by making a call to setAdapter. 

@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_grid_view);
        Integer[] imagesIDs = {
                R.drawable.ttronslien0749,
                R.drawable.ttronslien0907,
                R.drawable.ttronslien3623,
                R.drawable.ttronslien6329,
                R.drawable.ttronslien6724,
                R.drawable.ttronslien6874,
        };
        GridView gridView = (GridView) findViewById(R.id.gridView1);
        gridView.setAdapter(new ImageDispalyAdapter(this, imagesIDs));
}

Here’s how the GridView sample gets rendered on emulator.

GridView

Tips and Best Practices

1. When it comes to selection of the layouts, the most preferred one is RelativeLayout because it’s very flexible enough to render in screens with various display size. 

2. Using AbsoluteLayouts are not so recommended and in-fact it’s deprecated. But instead you can make use of other layout types such as FrameLayout, RelativeLayout etc.

3. Do not nest too much of LinearLayout types as it will hit the performance and end up in slow draw. But instead try to simplify the layout with other alternatives like using RelativeLayouts and simplify the layout hierarchy. The lesser the layout hierarchy, the quicker it gets rendered. 

4. When you are using a RelativeLayout, yet times you will face a circular dependency error. This happens for example you might be setting layout_above and layout_below for a control. You can only specify one but not both else you it lead in to a circular dependency. 

5. When you are using a TableLayout, set the layout_height and layout_width at the layout level only. Set the layout_weight to control the width settings for the view elements within the TableRow so that you can control the TableLayout width.

6. Its good practice to store all string values used within the layout xml file in a string.xml resource file. 

7. When using text sizes for UI components, always keep in mind to use 'dp' (density independent pixel) or 'sp' (scale independent pixel) and do not use 'px' because it will never scale as per the screen size.

Note - when you are using 'sp', the size is scaled by the user's prefered text size. Also the unit 'dp' is an abstract virtual pixel unit, when used the size is set based on the physical density of the device and it varies by device. one 'dp' is one pixel in 160 dp screen. The advantages of using 'dp' is it scales as per the current screen density. Also the 'sp' too scales but it's scaled as per the user's font preference.

Using Hierarchy Viewer

Let us discuss about the Hierarchy viewer, it’s a small tool which is available under “Android\android-sdk\tools”.  It’s a layout performance tool one can make use of it to analyze the application layout performance when the app running. It helps to discover various performance bottlenecks while rendering the layouts.  Please note – The hierarch viewer is deprecated, you will have to run monitor.bat file which combines many other things along with viewing hierarchy. 

Here’s how you run the hierarch viewer. 

1.    Connect your device or Start the emulator.

2.    Navigate to Android SDK -> tools folder and double click on hierarchyviewer.bat file , which will trigger in making a call to hierarchyviewer2.jar 

3.    Now launch the application. You will see the hierarchy viewer showing the device with the processes.

4.    Sometimes you will have to click on refresh button to show the list of devices.

HierarchViewer1

5.    Select and double click on the application that you wish to view the hierarch. You will have to click on the ‘Profile Node’ button which will show the measure, layout and draw timings in milliseconds. 

HierarchViewerForGridView

When you click on the GridView Layout, as show above it will show the measure, layout and draw times for the selected node and also for all its children’s. When you click on the profile node button, you will see three dots showing the measure, layout and draw times. It looks exactly like a traffic light with red, yellow and green. You should be looking for the red dots and see how you can optimize to render quickly with less time. 

Now we will see the biggest performance killer that can expect if you are using nested view elements such as LinearLayout which leads to deep hierarchy. Instead you should try to simplify the view layout without much deep hierarchy by using RelativeLayouts.  Yet times there might be some other issues in the code too which affects the performance. We will see these things with a real example.
Here’s the snapshot of the hierarchy viewer for our sample LinearLayout application with four TextView elements. You could see below, in total it took 10ms to draw and measure the LinearLayout with child TextView with the text size set with pixel. 

Note - The application is purposely designed with TextView set with text size as pixels (px) and hence we see some red dots which is affecting the performance. We will see next how to improve our code to fix the performance issues.

HierarchViewerForLinearLayoutWith_px

Using Lint

Lint is a static analysis tool which one can on a selected project file or complete project level to understand the potential coding improvements that one can do to improve security, performance, usability, accessibility etc. Here’ the lint output for our LinearLayout sample with text size set with pixel.
 

LintForLinearLayoutSample1


You will notice above that we need to avoid the ‘px’ dimension and instead we can make use of dp (device independent pixel) or sp (scale independent pixel).

When we change our sample LinearLayout app to use ‘sp’ dimension for the text size and run the hierarch for the same, below is what you see. Note – Now you don’t see the measure time taken.

 

HierarchViewerForLinearLayoutWith_sp

Generally speaking one has to run lint and fix all the suggestions so that we can improve our code and avoid some of the common usability and performance issues.


UI Controls

Now let us take a look into the user interface controls.

Edit Text

The EditText is a view element which is used to input some texts into your application. You can either enter a single line or a multiline depending on the edit text property set. On placing a cursor on an edit text, we can present the user with the most suitable virtual keyboard. 

The inputType property is what that determines the type of keyboard that has to be shown; certain characters are shown in one type and may not be in others ex: The email address type shows a ‘@’ character. Were as in a number type keyboard, you will only see a virtual keyboard with all numbers that one can key in. 

Here are different types that one can set for an EditText inputType property.
 

1.    text – Default text keyboard.
2.    textEmailAddress - Text keyboard with the @ character.
3.    textUri - Normal text keyboard with the / character.
4.    number - Number keypad.
5.    phone - Phone style keypad.


Properties of EditText 

 

  • id – The id refers to the uniquely identify the edit text. Ex:android:id="@+id/editTextUserName".
  • hint – The hint property is set with a text, it helps the user in understanding what needs to be inputted.  
  • focused – makes the edit text to focus by default.
  • fontfamily – Used to set the font. Ex: android:fontFamily="sans-serif-thin".      
  • gravity – The gravity refers to how the text should be displayed. You can set with left, right, center etc.
  • height – Specifies the height of the edit text. Ex - 30sp.
  • width – Specifies the width of the edit text. Ex – 30sp.
  • inputType – When sets , it allows the virtual key board to be displayed with the specified type. Ex – textEmailAddress, textMultiLine. 
  • text – Used to set some text to be displayed.
  • textSize  - Used to set the text size. Signifies how large the text should be displayed.
  • textColor – Used to set the color of text which means the foreground color. 
  • textStyle – set the text style with the possible variants ex: Normal, Bold, Italic.
  • padding – Sets the space with in the edit text for all or left, right, bottom, top.
  • paddingStart - Sets the spacing at the beginning of the edit text.
  • paddingEnd - Sets the spacing at the end of the edit text.
  • password – If set with a true value, shows the edit text as a password box.
  • phoneNumber – when set, shows a phone number keyboard on selection of the edit text box.
  • singleLine – Specifies the edit text to be of single line.
  • visibility – Sets the visibility of the edit text. You can set with visible, invisible or gone.
  • selectAllOnFoucs – When set to true, on focus of the edit text, the whole text will be selected.
  • background – Used to set the edit text background color.
  • capitalize – When set to true, will capitalize all texts.
  • ems – Refers to the font size. 
  • maxLength – Specifies how many characters are allowed to key in.
  • maxHeight –  Specifies how many pixel tall the edit text should be.
  • minHeight –  Specifies the edit text to be a minimum of the specified amount of pixel tall.
  • maxLines – Specifies the edit text to stand the specified amount of lines tall. 
  • minLines – Specifies the edit text to be a minimum of the specified amount of lines tall.

Let us see with an example, how to code a simple log on screen with two EditText boxes to accept user name and password.

1.    Create a new project with a blank layout.

2.    Open up the layout file. You can drag and drop text fields and set the properties as applicable or use the below code to create a username and password edit text boxes. 

<EditText
        android:layout_width="323dp"
        android:layout_height="40sp"
        android:inputType="textPersonName"
        android:text=""
        android:ems="10"
        android:id="@+id/editTextUserName"
        android:layout_marginTop="60dp"
        android:layout_below="@+id/textWelcome"
        android:layout_alignParentStart="true"
        android:layout_alignParentEnd="true"
        android:layout_x="20dp"
        android:layout_y="103dp"
        android:hint="User Name"
        android:focusable="true"
        android:password="false" />

<EditText
        android:layout_width="350dp"
        android:layout_height="40sp"
        android:inputType="textPassword"
        android:ems="10"
        android:id="@+id/editTextPassword"
        android:layout_below="@+id/editTextUserName"
        android:layout_alignEnd="@+id/btnSignIn"
        android:layout_marginTop="41dp"
        android:layout_alignParentStart="true"
        android:layout_x="20dp"
        android:layout_y="187dp"
        android:hint="Password" />

Here’s the snapshot of how our application looks like.

EditText

Auto complete Text view

The AutoCompleteTextView element is used to create an editable text box with an autocomplete feature. It makes the text box to automatically show some suggestions when the user keys in some text. Behind the scene an adapter is being used to set the auto complete text views adapter so that it can show suggestions. 

AutoCompleteTextView is a view element created by extending EditText. Hence it has all the properties of edit text inherited. Let us take a look into some of the unique properties of AutoCompleteTextView.

Properties of auto complete text

completionHint    - Specifies the hint to be displayed in the drop down menu.
completionHintView – Specifies the hint view to be displayed in the drop down menu.
completionThreshold – The number of characters that the user must type before completion suggestions are displayed in a drop down menu. You don’t have to always set this property.
dropDownAnchor – When set, it makes the view to anchor the auto-complete dropdown.
dropDownHeight- Sets the height of the dropdown.
dropDownWidth – Sets the width of the dropdown.
dropDownHorizontalOffset – Sets the amount of pixels by which the drop down should be offset horizontally. dropDownVerticalOffset – Sets the amount of pixels by which the drop down should be offset vertically. 

Now let us take a look into an example. We will be creating a single auto complete text displaying days name as suggestions when the user keys in days name.

1.    Create a new project with a blank layout.

2.    Open up the layout file and code the auto complete text view as below.

<AutoCompleteTextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/editAutoCompleteText1"
        android:layout_alignParentTop="true"
        android:layout_alignParentStart="true"
        android:layout_marginTop="50dp"
        android:layout_alignParentEnd="true"
        android:hint="Day name"
        android:minLines="2" />

3.    Now let us code the activity class file to set the auto complete adapter to show days suggestions. Here’s the code snippet for the same. We are writing our code within the onCreate override. 

1.    We will be creating a list of string and add all the days to it.

2.    Next, we will be creating an instance of an ArrayAdapter of string type with passing in a view and days collection.

3.    Next we will getting a reference to our auto complete text view and make a call setAdapter passing in the days adapter that we had created in step 2.

@Override
protected void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.activity_autocomplete_text_view);
        List<String> days = new ArrayList<String>();
        days.add("Monday");
        days.add("Tuesday");
        days.add("Wednesday");
        days.add("Thursday");
        days.add("Friday");
        days.add("Saturday");
        days.add("Sunday");
        ArrayAdapter<String> daysAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_dropdown_item_1line, days);
        AutoCompleteTextView autoCompleteTextView = (AutoCompleteTextView)
                findViewById(R.id.editAutoCompleteText1); autoCompleteTextView.setAdapter(daysAdapter);
}

Here’s the snapshot of our auto complete text view sample. Note – The texts are not case sensitive, as long as the user key in text matches with the autocomplete list item, it will show the drop down with suggested items.

AutoCompleteTextView

Button 

A button in an android represents a push button. You can click or press a button to perform an action. A button is always associated with an action to be performed when the user clicks or press on it. 

Let us have a look into an example to understand how the button element can be used. 

1.    Create a new project with a blank layout.

2.    Drag and drop button widget or add the below code and set the respective properties that you need. 

<Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Say Hello"
        android:id="@+id/btnSayHello"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true"
        android:gravity="center"
        android:minLines="3"
        android:minWidth="5dp"
        android:textColor="#ff351bff"
        android:textSize="20sp"
        android:textStyle="bold"
        android:hint="Say Hello"
        android:padding="20dp"
        android:shadowColor="#ffff6148" />

3.    Now let us write some code in activity class file to handle the button onClick event. Here’s the code snippet for the same.

1.    Here are the packages that we need to import for this sample. The OnClickListener is a part of the View package. In order to show a Toast message, we need to import Toast package.

import android.view.View;
import android.widget.Button;
import android.widget.Toast;

2.    Get a reference to our button widget – btnSayHello with the help of findViewById.
3.    Make a call to setOnClickListener of button to handle the on click event.  
4.    Write code to display a Toast message ‘Hello World’ with in the onClick method or View.OnClickListener

@Override
protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_button);
        Button btnSayHello = (Button) findViewById(R.id.btnSayHello); btnSayHello.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Toast.makeText(getApplicationContext(), "Hello World!", Toast.LENGTH_SHORT).show();
            }
        });
}

Here’s the snapshot of our button sample application running on emulator. When you click on the ‘Say Hello’ button, it will show a Toast message with ‘Hello World!’

Button

ImageButton  

An ImageButton is a button with an image. The behavior of an Image button is exactly same as that of a normal button.
 
Let us see an example to see the usage of an ImageButton.  

1. Create a new project with a blank layout. 

We will be making use of CodeProject bob logo which you will see in res/drawable-hdpi folder. 
Drag and drop ImageButton widget or add the below code and set the respective properties that you need.  You can see below, the image button src i.e source property is set with our bob logo. 

<ImageButton 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="Say Hello" 
        android:id="@+id/btnSayHello" 
        android:layout_centerVertical="true" 
        android:layout_centerHorizontal="true" 
        android:gravity="center" 
        android:src="@drawable/boblogo"/> 

2. Now let us write some code in activity class file to handle the button onClick event. Here’s the code snippet for the same. 
 
Here are the packages that we need to import for this sample. The OnClickListener is a part of the View package. In order to show a Toast message, we need to import Toast package. 

import android.view.View; 
import android.widget.ImageButton; 
import android.widget.Toast; 

Get a reference to our image button widget – btnSayHello with the help of findViewById. 
Make a call to setOnClickListener method of image button instance to handle the on click event.   
Write code to display a Toast message ‘Hello World’ with in the onClick method or View.OnClickListener  

@Override 
protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.activity_button); 
        ImageButton btnSayHello = (ImageButton) findViewById(R.id.btnSayHello); btnSayHello.setOnClickListener(new View.OnClickListener() { 
            public void onClick(View v) { 
                Toast.makeText(getApplicationContext(), "Hello World!", Toast.LENGTH_SHORT).show(); 
            } 
        }); 
}  

Here’s snapshot of our image button sample. When you click on the image button, it will show a toast message with ‘Hello World!’ 

ImageButton

CheckBox  

A checkbox is a view class which inherits itself from a compound button. It’s a button with two states, either checked (returns true) or un-checked (return false). By default the checkbox state will be un-checked. The checkbox has inherits all the properties of a Button class.  

Let us see with an example on how to use a checkbox.  

1. Create a new project with a blank layout. 

2. Open up the layout xml file and make a change to use AbsoluteLayout and use the below code or drag and drop to create a checkbox view element. Here’s the code snippet which creates three checkboxes with a text ‘C#’, ‘Java’, ‘PHP’ and ‘Perl’.

<CheckBox 
        android:id="@+id/chkCSharp" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:checked="true" 
        android:textColor="#ffffff" 
        android:text="C#" 
        android:layout_x="8dp" 
        android:layout_y="110dp" /> 
<CheckBox 
        android:id="@+id/chkJava" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="Java" 
        android:textColor="#ffffff" 
        android:layout_y="150dp" 
        android:layout_x="8dp" /> 
<CheckBox 
        android:id="@+id/chkPHP" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="PHP" 
        android:textColor="#ffffff" 
        android:layout_y="190dp" 
        android:layout_x="8dp" /> 
<CheckBox 
        android:id="@+id/chkPerl" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="Perl" 
        android:textColor="#ffffff" 
        android:layout_y="236dp" 
        android:layout_x="8dp" /> 

3. Now let us code the activity class file to see which checkboxes are checked and display a toast message for the same. Here’s what we do 

1. First we will be getting a reference to the button component and handle the onClick event. 

2. Next, we are getting a reference to all four checkboxes so that we can make a call to isChecked() method to see whether the checkbox is checked or not. If this function returns true, which means the checkbox is checked. 

3. We are making use of a StringBuilder and append a text based on the selected checkboxes and finally display a toast message for the same. 

// Get a Reference to Submit button 
Button btnSubmit = (Button)findViewById(R.id.btnSubmit); 

// Handle OnClick event 
btnSubmit.setOnClickListener(new View.OnClickListener() { 
      public void onClick(View v) { 
          
          // Get Reference to all Checkboxes used in layout file. 
          CheckBox chkCSharpe = (CheckBox) findViewById(R.id.chkCSharp); 
          CheckBox chkJava = (CheckBox) findViewById(R.id.chkJava); 
          CheckBox chkPHP = (CheckBox) findViewById(R.id.chkPHP); 
          CheckBox chkPerl = (CheckBox) findViewById(R.id.chkPerl); 
          
          // Use a StringBuilder instance to append all the selected checkbox items 
          StringBuffer resultStringBuilder = new StringBuffer(); 
          resultStringBuilder.append("Your favorite programming: "); 
          
          // If Checked = true, then we are appending text. 
          if(chkCSharpe.isChecked()) 
               resultStringBuilder.append("CSharp, "); 
          if(chkJava.isChecked()) 
               resultStringBuilder.append("Java, "); 
          if(chkPHP.isChecked()) 
               resultStringBuilder.append("PHP, "); 
          if(chkPerl.isChecked()) 
               resultStringBuilder.append("Perl, "); 
          
          // Display a Toast message. Strip off last comma and a space 
          Toast.makeText(getApplicationContext(), resultStringBuilder.substring(0, resultStringBuilder.length()-2), 
          Toast.LENGTH_LONG).show(); 
     } 
}); 

Here’s the snapshot of the checkbox sample application running on an emulator.  

CheckBox

Toggle Button 

A ToggleButton is used to displays a button with either “ON” or “OFF” state. It’s the most useful and an alternative for radio button to select and un-select just by toggling the ToggleButton. Within the code you can check whether the toggle button is ‘on’ or ‘off’ with the help of isChecked() method. The ToggleButton inherits itself from widget CompoundButton, which in-turn inherits from widget Button. Hence the ToggleButton has all the properties of a standard Button element. 

Some interesting properties of ToggleButton are  

  • textOn – It’s set with a text to be displayed when the toggle buttons state is ‘ON’.
  • textOff – it’s set with a text to be displayed when the toggle buttons state is ‘OFF’.
  • checked – When set to true, will make the toggle buttons state as ‘ON’

Let us take a look into an example to understand the usage of ToggleButton. 

1. Create a new project with a blank layout. 

2. Drag and drop ToggleButton and set the required properties or use the following code. You can see below, we have set the textOn and textOff property with a text which gets displayed on toggle ‘on’ or ‘off’. 

<ToggleButton  
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:id="@+id/toggleVibrateButton" 
        android:layout_alignParentTop="true" 
        android:layout_marginTop="164dp" 
        android:layout_alignParentStart="true" 
        android:textOn="Vibrate on" 
        android:textOff="Vibrate off" 
        android:textSize="30dp"/>

3. Let us write some code to handle toggle click. We will be writing code with in the onCreate override of our activity class file. Here’s the code snippet for the same. 
 
First we need to get a reference to our ToggleButton. It’s done with the help of findViewById 
Make a call to setOnClickListener method of ToggleButton instance to handle the on click event.   

The isChecked() method of toggle button returns true or false depending upon the toggle state. We will be displaying the Toast message ‘ON’ or ‘OFF’ based on the isChecked() return value. 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.activity_toggle_button); 
        ToggleButton vibrateToggleButton = (ToggleButton)findViewById(R.id.toggleVibrateButton); 
        vibrateToggleButton.setOnClickListener(new View.OnClickListener() { 
            public void onClick(View v) { 
                if (((ToggleButton) v).isChecked()) 
                    Toast.makeText(getApplicationContext(),"Vibrator is ON", 
                            Toast.LENGTH_LONG).show(); 
                else 
                    Toast.makeText(getApplicationContext(),"Vibrator is OFF", 
                            Toast.LENGTH_LONG).show(); 
            } 
        }); 
} 

Here’s the snapshot of the ToggleButton sample running on emulator.  

ToggleButton


Radio Button and Radio Group 

The RadioButton is a widget which had two states either checked or unchecked. The RadioButtons are generally used with RadioGroup (which acts as a container to hold all the radio buttons), so that we can group our RadioButtons with in the RadioGroup and let the user choose select one among other; which means if you have more than one radio buttons within radio group, you can only set one of them as checked. The radio buttons, unlike check boxes won’t let you uncheck once you select one and when it gets checked.  

Let us take a look into coding sample RadioButton with RadioGroup app.  

1. Create a new project with a blank layout. 

2. Open up the layout xml file. Use the below code to have a RadioGroup element 

<RadioGroup 
       android:layout_width="fill_parent" 
       android:layout_height="167dp" 
       android:layout_y="50dp"> 
</RadioGroup> 

3. Now let us drag and drop or use the below code to have a RadioButton within the RadioGroup. Then set the text, textSize etc. properties.  

<RadioButton 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="C#" 
        android:id="@+id/rbCSharp" 
        android:layout_alignParentTop="true" 
        android:layout_alignParentStart="true" 
        android:layout_marginTop="42dp" 
        android:checked="true" 
        android:textSize="20sp" /> 

<RadioButton 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="Java" 
       android:id="@+id/rbJava" 
        android:layout_marginTop="34dp" 
        android:checked="false" 
        android:textSize="20sp" 
        android:layout_below="@+id/rbCSharp" 
        android:layout_alignParentStart="true" /> 

Now let us add a button element and handle the on click event and display the selected radio button as a toast message. 

Let us now code the onCreate override of our activity as below. Within the onClick button event, we will be getting a reference to RadioButtons then by making a call to isChecked() method, we will determine if the radio button is selected or not.  

@Override 
protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.activity_radio_button); 
        
        // Get a Reference to Submit button 
        Button btnSubmit = (Button)findViewById(R.id.buttonSubmit); 
        
        // Handle OnClick event 
        btnSubmit.setOnClickListener(new View.OnClickListener() { 
           public void onClick(View v) { 
                
                // Get Reference to all RadioButtons used in layout file. 
                RadioButton rbCSharp = (RadioButton) findViewById(R.id.rbCSharp); 
                RadioButton rbJava = (RadioButton) findViewById(R.id.rbJava); 
 
                if(rbCSharp.isChecked()) 
                    Toast.makeText(getApplicationContext(), "You have selected CSharp", 
                        Toast.LENGTH_LONG).show(); 
                else if(rbJava.isChecked()) 
                    Toast.makeText(getApplicationContext(), "You have selected Java", 
                            Toast.LENGTH_LONG).show(); 
            } 
        }); 
} 

Here’s snapshot of our RadioButton with RadioGroup sample application. 

RadioButtonAndRadioGroup


ProgressBar

A ProgressBar is a view element which can be used to visually show the progress of some background operations as a horizontal moving bar indicating how far the operation has completed. You can either go with displaying a horizontal or circular progress.  

ProgressBar can be in an intermediate mode. It’s used when you do not know how long the operation is going to be. Say for example you are trying to download a music file, depending upon the network connection speed, the time taken to download may vary, in such cases you can go with setting a progress bar with intermediate mode as true. With intermediate mode, the actual progress is not shown but still there will be a visual cue to be specific a cyclic animation is show. Say if you are using a circular progress bar, it will keep rotating and once you have completed the operation, you can set the progress bar to become invisible.  

Let us see with an example on how to create a simple progress bar. We will be creating a circular and a horizontal progress bar. 

1. Create a new project with a blank layout. 

2. Open up the layout xml file and use the below mentioned code blocks to create a progress bar. Alternatively you could also drag and drop progress bar to your layout xml file in design mode. 

<ProgressBar 
        style="?android:attr/progressBarStyleHorizontal" 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:id="@+id/progressBar2" 
        android:layout_alignParentStart="true" 
        android:layout_below="@+id/progressBar1" 
        android:layout_alignParentEnd="true" 
        android:indeterminate="false"
        android:background="@drawable/blue"/>

Now let us start coding the activity class file to create some progress bar movements. Here’s the onCreate override code. First we have to get a reference to both of our progress bars. Then start a new thread to simulate the progress bar update with some delay and loop through a specific time interval so as to create an effect as if there’s some job or work is taking place.  

@Override 
protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.activity_progress_bar); 
        progressBar2 = (ProgressBar) findViewById(R.id.progressBar2); 
        textViewDownloadMusic = (TextView) findViewById(R.id.textViewDownloadMusic);
        
        // Start a new Thread to simulate Progressbar Update 
        new Thread(new ProgressBarTask()).start(); 
}  ​

The thread needs to be created with a class which implements Runnable interface. Here’s the code snippet of our ProgressBarTask which implements Runnable interface. We just have to implement run method. Here’s what we do, set a counter to zero and loop through until specific interval of time. While you are looping, make the thread to sleep for an interval then increment the counter and update the progress bar using updateProgress method. 

private class ProgressBarTask implements Runnable { 
       @Override 
        public void run() { 
            try { 
                int waitTime = 0; 
                while( waitTime < ProgressBar_Timer) { 
                    Thread.sleep(250); 
                    waitTime += 100; 
                    updateProgress(waitTime); 
                } 
            } catch(InterruptedException e) { 
                e.printStackTrace(); 
            } 
            // Make ProgressBar invisible after completion. 
            handler.post(new Runnable() { 
                public void run() { 
                    progressBar1.setVisibility(View.INVISIBLE);
                    textViewDownloadMusic.setText("Download Complete!"); 
                } 
            }); 
        } 
}​

Here’s the code block for updating the progress bar. The progress bar is incremented based on the calculated value the max time of the progress bar (by default it’s 100) multiplied by the wait time and divide the whole by the specific progress bar time interval. The setProgress method is used to increment the progress bar.  

public void updateProgress(final int timePassed) { 
        final int progress1 = progressBar1.getMax() * timePassed / ProgressBar_Timer; 
        progressBar1.setProgress(progress1); 
} 

Once the loop gets completed and you don’t have a anything to update, you can make the progress bar to become invisible indicating the completion of task. This is done by making a call to setVisibility of progress bar to View.INVISIBLE. Also notice one thing; you won’t be able to make a direct call to the progress bar within another thread, the reason being the progress bar was created by the main thread. So we will be making use of a handler instance (which is a part of android.os.Handler) to make a call to set the visibility of progress bars. 
 
Here’s the snapshot of our sample progress bar application. 

ProgressBar

Spinner  

The spinner in android provides a very easy way to pick a spinner list item from the available ones. You can think of a spinner as a drop down list of spinner components that one can select. When the user clicks or touch on the spinner, it will show a list of values. You can either create a spinner list based on the hardcode string array resource or you can go with creating one dynamically within the code.  

Let us see with an example in building a simple spinner which is created dynamically by coding the activity class file. 

1. Create a new project with a blank layout. 

2. Drag and drop the snippet or use the below code to create a new spinner in your layout activity file. Notice the background color which is being set for the spinner and the pop up spinner list. 

<Spinner 
        android:id="@+id/spinner1" 
        android:layout_width="fill_parent" 
        android:layout_height="wrap_content" 
        android:background="#000000" 
        android:dropDownSelector="#ff241d0e" 
        android:popupBackground="#ff402212" />

3. We will be writing a code to create a spinner list. Here’s the code snippet for the same. Here’s what we do. 

1. Get a reference to spinner so that we can set its adapter.  
2. Build a day’s list of string by adding the day name starting from Monday to Sunday.  
3. Create a new ArrayAdapter of type string with the context, simple spinner drop down layout and days. 

At last we will be making a call to setAdapter passing in the ArrayAdapter that we had created in step 3. 

@Override 
protected void onCreate(Bundle savedInstanceState) { 
        super.onCreate(savedInstanceState); 
        setContentView(R.layout.activity_spinner);        
        Spinner spinner = (Spinner)findViewById(R.id.spinner1); 
        List<String> days = new ArrayList<String>(); 
        days.add("Monday"); 
        days.add("Tuesday"); 
        days.add("Wednesday"); 
        days.add("Thursday"); 
        days.add("Friday"); 
        days.add("Saturday"); 
        days.add("Sunday"); 
        ArrayAdapter<String> stringArrayAdapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_dropdown_item, days); 
        spinner.setAdapter(stringArrayAdapter); 
}  

Let us now see how to add a spinner item selected listener. Here’s the code snippet for the same. You will have to make a call to setOnItemSelectedListener by setting an adapter view implementing OnItemSelectedListener interface.  We will be focusing on the onItemSelected method by displaying the selected day as a toast message.  

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener(){ 
            @Override 
            public void onItemSelected(AdapterView parent, View view, int pos, long id) { 
                Toast.makeText(parent.getContext(), "Selected Day : " + parent.getItemAtPosition(pos).toString(), Toast.LENGTH_SHORT).show(); 
            } 
            public void onNothingSelected(android.widget.AdapterView<?> adapterView){} 
}); 

Here’s the snapshot of the spinner demo application running on emulator.  

Spinner


TimePicker  

TimePicker is a widget which you can make use of it to select time in hour, minute with AM/PM depending upon 12/24 hour format. When you are using a TimePicker, it shows an easy to use user interface though you can scroll and select a time.  

Let us see with an example to understand the usage of time picker. We will also be using a TimerPickerDialog , you can use it to show as a time picker dialog and let the user select the time.  

1. Create a new project with a blank layout. 

2. Open up the layout xml file and remove everything in it as we will be making use of LinearLayout for this sample. Add the below code snippet to show a TimePicker , two buttons one to get current time and the other to show a time picker dialog. 

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"    xmlns:tools=&rdquo;http://schemas.android.com/tools&rdquo; 
    android:layout_width="fill_parent" 
    android:layout_height="fill_parent" 
    tools:context=".TimePickerActivity" 
    android:background="#f90" 
    android:orientation="vertical"> 
    <TextView 
        android:layout_width="wrap_content" 
        android:layout_height="50sp" 
        android:id="@+id/txtTimePicker" 
        android:textSize="30sp" 
        android:text="TimePicker Demo" /> 
    <TimePicker 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:id="@+id/timePicker" /> 
    <Button 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="Get Current Time" 
        android:id="@+id/btnGetTime"/> 
     
<Button 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="Show TimePicker Dialog" 
        android:id="@+id/btnTimePickerDialog" /> 
</LinearLayout>

3. Now let us code the activity class file to display the TimePicker widget time and also to show a TimePickerDialog and handle the onClick listener.  Here’s what we code.  

First we need to get a reference to our TimePicker widget and a button to show the selected time for the same.   

final TimePicker timePicker1 = (TimePicker) findViewById(R.id.timePicker); 
Button btnGetTime = (Button) findViewById(R.id.btnGetTime); 
btnGetTime.setOnClickListener(new View.OnClickListener() { 
            public void onClick(View v) { 
                String time = timePicker1.getCurrentHour().toString() + ":" + timePicker1.getCurrentMinute().toString(); 
                Toast.makeText(TimePickerActivity.this, time, Toast.LENGTH_LONG).show(); 
            } 
}); 

Say if you wish the time picker widget to show the time in 24 hour view. You can code as below 

timePicker1.setIs24HourView(true);  

In-order to display the time from a time picker widget, we will have to make a call to setOnClickListener method of button with a new which implements OnClickListener interface. For now we will be getting the current hour and minute and display the same as a toast message. 

Here’s the snapshot for the time picker widget. 

TimePicker

Now let us code to show the time picker dialog when the user clicks on ‘Show TimePicker Dialog’ button.  Here’s the code snippet for the same. 

First we need to get a reference to a button, on click on which shows a time picker dialog. Next , we will be setting the on click listener with the code to get the current hour and minute based on the calendar instance and then we will be showing a time picker dialog with the activity reference, on time set listener, hour and minute.  

Button btnTimePickerDialog  = (Button) findViewById(R.id.btnTimePickerDialog); 
        btnTimePickerDialog.setOnClickListener(new View.OnClickListener() {             
          public void onClick(View v) { 
              Calendar c = Calendar.getInstance(); 
              int hour = c.get(Calendar.HOUR); 
              int minute = c.get(Calendar.MINUTE); 
              TimePickerDialog timePickerDialog = new TimePickerDialog(TimePickerActivity.this,  
timeSetListener, hour, minute,false); 
              timePickerDialog.show(); 
            } 
});

You might have noticed the timeSetListener which is nothing but a TimePickerDialog.OnTimeSetListener that we need to set. It’s required to handle the on time set so that when the user selects a time and clicks on ‘Done’ button on the time picker dialog, if we have the OnTimeSetListener set with, we can capture the selected time. Here’s the code snippet for the same. 

private TimePickerDialog.OnTimeSetListener timeSetListener = new 
     TimePickerDialog.OnTimeSetListener() { 
        public void onTimeSet(TimePicker view, int hourOfDay, int minuteOfHour) { 
           Toast.makeText(getBaseContext(), 
                    "You have selected : " + hourOfDay + ":" + minuteOfHour, 
                    Toast.LENGTH_SHORT).show(); 
        } 
}; 

Here’s the snapshot of the time picker dialog. 

TimePickerDialog


DatePicker  

The DatePicker is a widget which extends itself from a FrameLayout and is mainly used for selecting a date from a screen which renders a date picker UI.  You can select the data, month and year which you wish to just by selecting the same from spinners. The DatePicker has a property calendarViewShown which you can set it to false if you don’t want to show the calender view but by default it is set to true. 

Let us walk through an example to understand the usage of DatePicker. We will be also looking into how DatePickerDialog, which is a helpful component to show a dialog with an interface to select date. It’s like the DatePicker but provides a dialog which you can open up say with a button click etc. and it lets you select date and when you can click on ‘Done’ button to set the date. 

1. Create a new project with a blank layout. 

2. Open up the layout xml file and remove the default content. We will be making use of a TableLayout and add few view elements that is required as a part of the demo. 

<TableLayout xmlns:android=&rdquo;http://schemas.android.com/apk/res/android&rdquo; 
    xmlns:tools=http://schemas.android.com/tools 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    tools:context=".DatePickerActivity" 
    android:background="#f90"> 
    <TableRow 
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent"> 
        <DatePicker 
            android:layout_width="wrap_content" 
            android:layout_height="150dp" 
            android:id="@+id/datePicker1" 
            android:calendarViewShown="false" 
            android:layout_alignTop="@+id/datePicker1" 
            android:layout_centerHorizontal="true"/> 
    </TableRow> 
    <Button 
        android:layout_width="138dp" 
        android:layout_height="wrap_content" 
        android:text="Get Date" 
        android:id="@+id/btnGetDate" 
        android:layout_below="@+id/datePicker1" 
        android:layout_alignParentStart="false" 
        android:longClickable="false" 
        android:gravity="top" 
        android:layout_gravity="left|center_vertical" /> 
    <TableRow 
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent"> 
        <EditText 
            android:layout_width="wrap_content" 
            android:layout_height="wrap_content" 
            android:id="@+id/editDateText" 
            android:layout_below="@+id/btnGetDate" 
            android:layout_alignParentStart="true" 
            android:layout_alignParentEnd="true" 
            android:layout_column="0" /> 
    </TableRow> 
    <Button 
        android:layout_width="wrap_content" 
        android:layout_height="wrap_content" 
        android:text="Set Date With DatePicker Dialog" 
        android:id="@+id/setDateButton" 
        android:layout_below="@+id/editDateText" 
        android:layout_alignParentEnd="true" 
        android:layout_gravity="right|bottom" /> 
</TableLayout>  

3. Now let us code the activity class file to get the selected date from the DatePicker component and also you will see how to code to show up a DatePicker dialog, set the date in an edit text box. Here’s the code snippet for the same. 
 
First we will be getting a reference to our DatePicker and Button component. Then we will be handling the buttons on click event by making a call to setOnClickListener method passing in a new instance of a View which implements OnClickListener. Within the onClick method, we are getting the currently selected month and day of the month and displaying the same as a toast message.      

// Get Date 
final DatePicker datePicker1 = (DatePicker) findViewById(R.id.datePicker1); 
        Button btnGetTime = (Button) findViewById(R.id.btnGetDate); 
        btnGetTime.setOnClickListener(new View.OnClickListener() { 
            public void onClick(View v) { 
                String date = datePicker1.getMonth() + "-" + datePicker1.getDayOfMonth() + "-" + datePicker1.getYear(); 
                Toast.makeText(getApplicationContext(), date, Toast.LENGTH_LONG).show(); 
            } 
}); 

Here’s the snapshot of the UI showing the usage of DatePicker component. 

DatePicker

Now let us see the usage of a DatePicker dialog. We are making use of a button with a text ‘Set Date with DatePicker Dialog’. On click the button, we will be showing up a DatePicker dialog, which is similar to a DatePicker component but the dialog lets you to set date. When you are finished with setting the date and on click on ‘Done’ button, a code is written to handle the set date so that we are going to display the date on an edit text box. Here’s the code snippet for the same. 

// Set Date using DatePickerDialogfinal Button setDateButton= (Button)findViewById(R.id.setDateButton); 
final EditText txtDate= (EditText)findViewById(R.id.editDateText); 
setDateButton.setOnClickListener(new View.OnClickListener() { 
            public void onClick(View v) { 
                final Calendar c = Calendar.getInstance(); 
                int year = c.get(Calendar.YEAR); 
                int month = c.get(Calendar.MONTH); 
                int day = c.get(Calendar.DAY_OF_MONTH); 
                DatePickerDialog dtPicker = new DatePickerDialog(DatePickerActivity.this, 
                        new DatePickerDialog.OnDateSetListener() { 
                            @Override 
                            public void onDateSet(DatePicker view, int iYear, 
                                                  int iMonth, int iDay) { 
                                txtDate.setText(iDay + "-" + (iMonth + 1) + "-" + iYear); 
                            } 
                        }, year, month, day 
                ); 
               dtPicker.show(); 
            } 
}); 

Here’s the snapshot of the UI screen showing the DatePicker dialog usage.

DatePickerDialog


Reference 


The article code samples make use of CodeProject Bob Logo, which was taken from  

http://www.codeproject.com/Info/Stuff.aspx 

Here are links through which I got inspired and gained knowledge.  
 
https://developer.android.com/guide/topics/ui 
http://developer.android.com/reference/android 
http://www.tutorialspoint.com/android 
 
Here is the link to free images. Few of them, I had used in GridView sample application  
 
http://www.morguefile.com/archive 

Points of Interest

I have learnt a lot while working on this article. I strongly believe if one goes through all the concepts mentioned in details, will have an ease in developing andorid apps. 

Apart from the application development, there's one important thing which I need to stress you all that I learnt and gained knowledge in understanding the application performance by using andorid tools which has significantly helped me in viewing all the UI elements and layouts which took time to render and learnt how we can improve the same.

History

Version 1.0 - Initial version of the articles explaining all the required topics for Layouts and Controls - 08/17/2014.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

Ranjan.D
Web Developer
United States United States
Profile
 
Around 10 years of professional software development experience in analysis, design, development, testing and implementation of enterprise web applications for healthcare domain with good exposure to object-oriented design, software architectures, design patterns, test-driven development and agile practices.
 
In Brief
 
Analyse and create High Level , Detailed Design documents.
Use UML Modelling and create Use Cases , Class Diagram , Component Model , Deployment Diagram, Sequence Diagram in HLD.
 
Area of Working : Dedicated to Microsoft .NET Technologies
Experience with : C# , J2EE , J2ME, Windows Phone 8, Windows Store App
Proficient in: C# , XML , XHTML, XML, HTML5, Javascript, Jquery, CSS, SQL, LINQ, EF
 
Software Development
 
Database: Microsoft SQL Server, FoxPro
Development Frameworks: Microsoft .NET 1.1, 2.0, 3.5, 4.5
UI: Windows Forms, Windows Presentation Foundation, ASP.NET Web Forms and ASP.NET MVC3, MVC4
Coding: WinForm , Web Development, Windows Phone, WinRT Programming, WCF, WebAPI
 
Healthcare Domain Experience
 
CCD, CCR, QRDA, HIE, HL7 V3, Healthcare Interoperability
 
Others:
 
TTD, BDD
 
Education
 
B.E (Computer Science)
 
CodeProject Contest So Far:
 
1. Windows Azure Developer Contest - HealthReunion - A Windows Azure based healthcare product , link - http://www.codeproject.com/Articles/582535/HealthReunion-A-Windows-Azure-based-healthcare-pro
 
2. DnB Developer Contest - DNB Business Lookup and Analytics , link - http://www.codeproject.com/Articles/618344/DNB-Business-Lookup-and-Analytics
 
3. Intel Ultrabook Contest - Journey from development, code signing to publishing my App to Intel AppUp , link - http://www.codeproject.com/Articles/517482/Journey-from-development-code-signing-to-publishin
 
4. Intel App Innovation Contest 2013 - eHealthCare - http://www.codeproject.com/Articles/635815/eHealthCare
 
5. Grand Prize Winner of CodeProject HTML5 &CSS3 Article Contest 2014
 
6. Grand Prize Winner of CodeProject Android Article Contest 2014

Comments and Discussions

 
QuestionExcellent article PinmemberMember 1118299427-Oct-14 2:20 
AnswerRe: Excellent article PinmvpRanjan.D27-Oct-14 4:50 
GeneralMy vote of 5 PinmemberAbhishek Nandy15-Aug-14 20:38 
GeneralRe: My vote of 5 PinmvpRanjan.D16-Aug-14 3:08 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web04 | 2.8.150305.1 | Last Updated 15 Aug 2014
Article Copyright 2014 by Ranjan.D
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid