Thursday, 6 June 2013

Android Layouts

In this post I will be discussing about the different view layouts in an android mobile application. The six different layouts are
1. Linear Layout
2. Relative Layout
3. Table Layout
4. Grid View
5. Tab Layout
6. List View

Android allows you to create view layouts using simple XML file (we can also create a layout using java code). All the layouts must be placed in /res/layout folder.
Android Layout Directory
Okay, now lets get started with the view layouts.

1. Linear Layout
In a linear layout, like the name suggests, all the elements are displayed in a linear fashion(below is an example of the linear layouts), either Horizontally or Vertically and this behavior is set in android:orientation which is an attribute of the node LinearLayout.
Example of Vertical layout snippet
<LinearLayout android:orientation="vertical"> .... </LinearLayout>
Example of Horizontal layout snippet
<LinearLayout android:orientation="horizontal"> .... </LinearLayout>
Android Layout
Now that we know the two types of linear layouts, here are the steps you need to follow to create them
1. Create a new project File -> New -> Android Project
2. In Package Explorer right click on res/layout folder and create a new Android XML File and name it as you wish. I am naming it as “linear_layout.xml”
res/layout -> Right Click -> New -> Android XML File
3. Now open newly created xml file (in my case “linear_layout.xml”) and type the following code.
<?xml version="1.0" encoding="utf-8"?>
<!-- Parent linear layout with vertical orientation -->
<LinearLayout
  android:orientation="vertical"
  android:layout_width="match_parent"
  android:layout_height="match_parent">
   
  <TextView android:layout_width="fill_parent" android:layout_height="wrap_content"
            android:text="Email:" android:padding="5dip"/>
             
  <EditText android:layout_width="fill_parent" android:layout_height="wrap_content"
            android:layout_marginBottom="10dip"/>           
   
  <Button android:layout_width="fill_parent" android:layout_height="wrap_content"
            android:text="Login"/>
   
  <!-- Child linear layout with horizontal orientation -->
  <LinearLayout android:layout_width="fill_parent"
                      android:layout_height="wrap_content"
              android:orientation="horizontal" android:background="#2a2a2a"
              android:layout_marginTop="25dip">
                 
  <TextView android:layout_width="fill_parent" android:layout_height="wrap_content"
         android:text="Home" android:padding="15dip" android:layout_weight="1"
         android:gravity="center"/>
             
  <TextView android:layout_width="fill_parent" android:layout_height="wrap_content"
         android:text="About" android:padding="15dip" android:layout_weight="1"
         android:gravity="center"/> 
   
  </LinearLayout>
     
</LinearLayout>
4. To set this newly created view as the initial view of your app, Open your MainActivity.java file. You would see the following line inside the onCreate function setContentView(R.layout.main). Change R.layout.main to R.layout.yourlinearviewname. In my case its R.layout.linear_layout
package com.example.androidlayouts;
import android.app.Activity;
import android.os.Bundle;
 
public class AndroidLayoutsActivity extends Activity {
 
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.linear_layout);
    }
}
5. To run the application, right click on the project -> Run As -> 1. Android Application. You should see your newly created linear layout in the emulator.
Linear layout output

2. Relative Layout
In a relative layout every element arranges itself relative to other elements or a parent element.
As an example, lets consider the layout defined below. The “Cancel” button is placed relatively, to the right of the “Login” button parallely. Here is the code snippet that achieves the mentioned alignment (Right of Login button parallely)
Example code snippet
<Button android:id="@+id/btnLogin" ..></Button>
 
<Button android:layout_toRightOf="@id/btnLogin"
            android:layout_alignTop="@id/btnLogin" ..></Button>
Android relative layout
Here are the steps to create a relative layout
1. Create a new project File -> New -> Android Project
2. In Package Explorer right click on res/layout folder and create a new Android XML File and name it as you wish. I am naming it as “relative_layout.xml”
res/layout -> Right Click -> New -> Android XML File
3. Now open newly created xml file (in my case “relative_layout.xml”) and type the following code.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
                android:layout_width="fill_parent"
                android:layout_height="wrap_content">
 
    <TextView android:id="@+id/label" android:layout_width="fill_parent"
              android:layout_height="wrap_content" android:text="Email" />
 
    <EditText android:id="@+id/inputEmail" android:layout_width="fill_parent"
              android:layout_height="wrap_content" android:layout_below="@id/label" />
   
    <Button android:id="@+id/btnLogin" android:layout_width="wrap_content"
            android:layout_height="wrap_content" android:layout_below="@id/inputEmail"
            android:layout_alignParentLeft="true" android:layout_marginRight="10px"
            android:text="Login" />
 
    <Button android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:layout_toRightOf="@id/btnLogin"
            android:layout_alignTop="@id/btnLogin"  android:text="Cancel" />
             
    <Button android:layout_width="wrap_content" android:layout_height="wrap_content"
            android:layout_alignParentBottom="true" android:text="Register new Account"
            android:layout_centerHorizontal="true"/>
</RelativeLayout>
4. Same like before open your MainActivity.java file and set the layout to your newly created relative layout file. In my case its R.layout.relative_layout
setContentView(R.layout.relative_layout);
5. To run the application, right click on the project -> Run As -> 1. Android Application. You should see your newly created relative layout in the emulator.
Relative layout output

3. Table Layout
Table layouts in Android works in the same way HTML table layouts work. You can divide your layouts into rows and columns. Its very easy to understand. The image below should give you an idea.
Table layout
1. Create a new project File -> New -> Android Project
2. In Package Explorer right click on res/layout folder and create a new Android XML File and name it as you wish. I am naming it as “table_layout.xml”
res/layout -> Right Click -> New -> Android XML File
3. Now open newly created xml file (in my case “table_layout.xml”) and type the following code.
<TableLayout 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:shrinkColumns="*"  android:stretchColumns="*" android:background="#ffffff">
    <!-- Row 1 with single column -->
    <TableRow 
        android:layout_height="wrap_content" 
        android:layout_width="fill_parent" 
        android:gravity="center_horizontal"> 
        <TextView 
            android:layout_width="match_parent" android:layout_height="wrap_content"
            android:textSize="18dp" android:text="Row 1"  android:layout_span="3"
            android:padding="18dip" android:background="#b0b0b0"
            android:textColor="#000"/> 
    </TableRow> 
     
    <!-- Row 2 with 3 columns -->
    <TableRow 
        android:id="@+id/tableRow1" 
        android:layout_height="wrap_content" 
        android:layout_width="match_parent"> 
        <TextView 
            android:id="@+id/TextView04" android:text="Row 2 column 1"
            android:layout_weight="1" android:background="#dcdcdc"
            android:textColor="#000000"
            android:padding="20dip" android:gravity="center"/> 
        <TextView 
            android:id="@+id/TextView04" android:text="Row 2 column 2"
            android:layout_weight="1" android:background="#d3d3d3"
            android:textColor="#000000"
            android:padding="20dip" android:gravity="center"/>
        <TextView 
            android:id="@+id/TextView04" android:text="Row 2 column 3"
            android:layout_weight="1" android:background="#cac9c9"
            android:textColor="#000000"
            android:padding="20dip" android:gravity="center"/>
    </TableRow>
     
    <!-- Row 3 with 2 columns -->
    <TableRow 
        android:layout_height="wrap_content" 
        android:layout_width="fill_parent" 
        android:gravity="center_horizontal"> 
        <TextView 
            android:id="@+id/TextView04" android:text="Row 3 column 1"
            android:layout_weight="1" android:background="#b0b0b0"
            android:textColor="#000000"
            android:padding="20dip" android:gravity="center"/>
             
        <TextView 
            android:id="@+id/TextView04" android:text="Row 3 column 2"
            android:layout_weight="1" android:background="#a09f9f"
            android:textColor="#000000"
            android:padding="20dip" android:gravity="center"/> 
    </TableRow> 
     
</TableLayout>
4. Same like before open your MainActivity.java file and set the layout to your newly created table layout file. In my case its R.layout.table_layout
setContentView(R.layout.table_layout);
5. To run the application, right click on the project -> Run As -> 1. Android Application. You should see your newly created table layout in the emulator.
table layout output
I have just discussed Linear Layout, Relative Layout and Table Layout in this post. The remaining Grid View, Tab Layout and List View will be covered in the next article. Stay tuned!



Creating Your First Android App


Its a longstanding tradition that when learning a new programming language or a framework, the first program written is to display a ‘Hello World’ on screen. Its pretty easy with Android. We can create a Hello World program in Android with practically no coding at all. Here we will make our first Android app with some interesting functionality, rather than just a simple ‘Hello World’ app.
Create a new project
Open Eclipse
Go to File→New→Project
Expand Android Folder, select Android Project and click NextAndroid Project Structure
Create the project with following properties:
  • Project Name: First App
  • Build Target: Select a suitable platform. Here I’ve selected 2.3.3
  • Application Name: First App
  • Package Name: com.firstapp
  • Create Activity: MainActivity
  • Min SDK version: 5
 These properties can be explained as follows:
Project Name:
Name of your Project. Make it a descriptive one so that you can identify it from others. A directory of that name will be created in the Eclipse workspace which contains the project files.
Build Target:
Here we are specifying under which API level, we are going to develop our program. If we select 2.3, it means that we are developing our app with 2.3 API. We are able to use only the features of 2.3 framework in our app.
Application Name:
The name of our application. This name will be displayed for our application, when installed on a device.
  Package Name:
Its the name of the Java package in which our code is going to be organized. It is a method to organize Java classes into modules. ‘com.maindomain.subdomain’ is the common package naming convention.
Create Activity:
This is the name of the first Activity in our application. When our application runs, this activity will be called by the system by default.
Min SDK version:
By Minimum Android version, we are specifying the minimum version of Android that is capable of running our application.

Now click Finish. Our new project is created.
Creating a Run configuration
Go to Run→Run Configurations
Select Android Application in the left pane and click on the New Launch Configuration button as shown in the figure.First Android app
Add a suitable name for the new Run Configuration select your current project by clicking on browse.First Android app
Select Target tab
Click Automatic and select the target virtual device you’ve created before.
(If you want to debug your application in a hardware device then select Manual instead of Automatic)First Android app
Click Apply and Close the dialogue.
Now you’ve successfully created a Run Configuration of your project.
Now Run your app by selecting Run→Run or by clicking the Run button in the toolbar.First Android app
If you’ve opted for manual target selection in the Run Configuration setup, Android will present you a chooser from where you can choose your run target device. Choose your virtual device or the physical device and click OK.First Android app


Now the emulator will start, it will take some time to load. After loading you will see the lock screen. Drag the slider to unlock the screen. Now you can see your Activity in the screen.

Without writing even a line of code, we made our Hello World application. It is really amazing, isn’t it. Lets analyze those components in our project that made this happen.
Go to Package Explorer window in the Eclipse and open AndroidManifest.xml file in the root folder.
Open the AndroidMAnifest.xml tab in the bottom of the window. You will see the following code:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
<?xml version="1.0" encoding="utf-8"?>
    package="com.firstapp"
    android:versionCode="1"
    android:versionName="1.0" >
 
    <uses-sdk android:minSdkVersion="5" />
 
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name" >
        <activity
            android:name=".MainActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
 
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
 
</manifest>
(We will get into the details of each of these in later posts. For now just know the basic concept)
The AndroidManifest file is a road map for the Android OS, when your app starts executing. It tells the OS, details of your app. It contains all informations about your app such version name, application label, icon file, user permissions required, details about activities and services etc.
The first line is the XML version and encoding declaration. Next it specify the package name, version code and version name of the app. Then name of the application and the icon file is pointed. Next is the name and label of the Activity. Intent filter specifies that this Activity should start when the applcation is launched.
Now open MainActivity.java in the SRC folder under the package name. It will look like the code below:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
package com.firstapp;
 
import android.app.Activity;
import android.os.Bundle;
 
public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
}
First lines specifies our java package and next two lines is used to import required packages into our app. Code of our main activity starts by extending the Activity class. We are overriding the onCreate() method and calling the method by the superclass. Then we are calling setContentView() method and passing R.layout.main into it. It is the xml file where our UI is defined. This means that the file named main in layout directory in the res folder. This is how we access a resource programmatically in java.
Let us see how the UI of our application is defined. Open main.xml under res/layout folder.
By default you will see the graphical layout. Switch it to text layout by clicking on the main.xml tab at the bottom.
Heres the code for main.xml:
?
1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
 
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />
 
</LinearLayout>
As in the manifest file, first line defines the version and encoding used. Linear layout is one among many widget containers used in Android. It allows us to arrange widgets linearly on the screen. The width and height of the Linear Layout is set to fill the screen. TextView is the only widget used in our app. The text it displays is defined in a string resource. To see how, open /values/string.xml. Switch to text view by clicking string.xml tab.
Following code shows how string resources are defined in Android.
?
1
2
3
4
5
6
7
<?xml version="1.0" encoding="utf-8"?>
<resources>
 
    <string name="hello">Hello World, MainActivity!</string>
    <string name="app_name">First App</string>
 
</resources>
There are two strings defined here, with names ‘hello’ and ‘app-name’
String named hello is used for the TextView and app_name is used in the manifest file as label of application.
So, this is how a ‘Hello World’ program in Android can be made. Now we are going to make some changes in these to build our first app.
First open the main.xml file and make the following changes.
Add an id to the LinearLayout and  TextView widget so that we can programmaticaly refer it in Java.
?
1
2
3
4
5
6
7
8
9
10
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:id="@+id/background" >
<TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello"
        android:id="@+id/text1" />
Add three buttons to the layout:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
<Button android:layout_width="fill_parent"
        android:layout_height="wrap_content"
         android:id="@+id/test"
         android:text="@string/button_test" />
 
    <Button android:layout_width="fill_parent"
        android:layout_height="wrap_content"
         android:id="@+id/changecolor"
         android:text="@string/button_color" />
 
    <Button android:layout_width="fill_parent"
        android:layout_height="wrap_content"
         android:id="@+id/exit"
         android:text="@string/button_exit" />
We use three new string resource in this. We must define them in string.xml
Add these strings:
?
1
2
3
<string name="button_test">Test</string>
    <string name="button_color">Change Background</string>
    <string name="button_exit">Exit</string>
Save the project and go to graphical layout editor to see the changes. You will see a screen like this:
first android app_activity
Add a color file to the values folder and define a color
For this, right click on the values folder
Select New→File
Enter filename as colors.xml and click Finish
Enter this xml code in colors.xml and Save.
?
1
2
3
4
5
6
<?xml version="1.0" encoding="utf-8"?>
<resources>
 
    <color name="newcolor">#121289</color>
 
</resources>
Design of our UI is complete now. Three buttons are placed in our layout, but it does nothing when we click on them unless we add click event handler for the button.
There are several ways by which we can handle a click event in Android. Now we will use the simplest method.
Open layout.xml and add this code as attribute of each of the <Button>tag.
?
1
android:onClick="newClickHandler"
By this we are telling the compiler to execute a method newClickHandler() when the button is clicked.
We should define the newClickHandler() method in MainActivity.java.
Open MainActivity.java and add the following code:
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
   public void newClickHandler(View view){
        TextView text1=(TextView)findViewById(R.id.text1);
        LinearLayout background=(LinearLayout)findViewById(R.id.background);
        int s=view.getId();
        switch(s){
        case R.id.test:
            text1.setText("Its Working");
            break;
        case R.id.changecolor:
            background.setBackgroundResource(R.color.newcolor);
            break;
 
        case R.id.exit:
            finish();
            break;
 
}
We are defining a new method to handle the click event of all the buttons placed. It accepts an object of the type View as parameter. Then we create two references for the LinearLayout and TextView to use in our program. We use a method findViewById() for this. It will take an id as a parameter and return the View associated with the id. So text1 and background are the references for the TextView and LinearLayout respectively. The line int s=view.getId(); will get the id of the view that got clicked into a variable ‘s’ of integer type. Then we are testing the variable with switch statement to find which button was clicked. It will compare the value of s with ids of all the buttons to find a match. If a match is found it will execute the corresponding code. If the test button is clicked it will alter the text property of the TextView to show ‘Its Working’ on screen. If the ‘Change Background’ button is clicked, background resource of LinearLayout is set to show a color that we defined in the colors.xml. If ‘Exit’ button is clicked, finish() method is called, which exits the app.
Entering the above code will result in some error messages in Eclipse. This is because, to use LinearLayout, TextView, View etc. In our program, we need to import some packages at the beginning. Hovering on the error sign will tell you some packages are required to be imported. Click on it and you will get the option to import those packages. These are the packages that are required:
?
1
2
3
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
Save and run the project.
 first android app_screen
Congrats. We’ve successfully completed our first Android app. From this you’ve a basic idea on User Interface creation, resource creation and management, event handling etc. You can copy the final code given below.
Final Code:
/res/layout/main.xml
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical"
    android:id="@+id/background" >"
 
    <TextView
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello"
        android:id="@+id/text1" />
 
<strong>/res/values/strings.xml</strong>    <Button android:layout_width="fill_parent"
        android:layout_height="wrap_content"
         android:id="@+id/test"
        android:onClick="newClickHandler"
        android:text="@string/button_test" />
 
    <Button android:layout_width="fill_parent"
        android:layout_height="wrap_content"
         android:id="@+id/changecolor"
        android:onClick="newClickHandler"
        android:text="@string/button_color" />
 
    <Button android:layout_width="fill_parent"
        android:layout_height="wrap_content"
         android:id="@+id/exit"
        android:onClick="newClickHandler"
        android:text="@string/button_exit" />"
 
</LinearLayout>
<strong></strong>
<strong></strong>
/res/values/strings.xml
?
1
2
3
4
5
6
7
8
9
<?xml version="1.0" encoding="utf-8"?>
<resources>
 
    <string name="hello">Hello World, MainActivity!</string>
    <string name="app_name">First App</string>
    <string name="button_test">Test</string>
    <string name="button_color">Change Background</string>
    <string name="button_exit">Exit</string>
</resources>
/res/values/colors.xml
?
1
2
3
4
5
6
<?xml version="1.0" encoding="utf-8"?>
<resources>
 
    <color name="newcolor">#121289</color>
 
</resources>
MainActivity.java
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
package com.firstapp;
 
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
 
public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
    }
    public void newClickHandler(View view){
        TextView text1=(TextView)findViewById(R.id.text1);
        LinearLayout background=(LinearLayout)findViewById(R.id.background);
        int s=view.getId();
        switch(s){
        case R.id.test:
            text1.setText("Its Working");
            break;
        case R.id.changecolor:
            background.setBackgroundResource(R.color.newcolor);
            break;
 
        case R.id.exit:
            finish();
            break;
 
        }
 
    }
}