MAD Unit - 2
MAD Unit - 2
MAD Unit - 2
Introduction to Layouts:
The basic building block for user interface is a View object which is created from the
View class and occupies a rectangular area on the screen and is responsible for drawing and event
handling. View is the base class for widgets, which are used to create interactive UI components
like buttons, text fields, etc.
The ViewGroup is a subclass of View and provides invisible container that hold other Views or
other ViewGroups and define their layout properties.
At third level we have different layouts which are subclasses of ViewGroup class and a typical
layout defines the visual structure for an Android user interface and can be created either at run
time using View/ViewGroup objects or you can declare your layout using simple XML
file main_layout.xml which is located in the res/layout folder of your project.
Layout Params:
This tutorial is more about creating your GUI based on layouts defined in XML file. A
layout may contain any type of widgets such as buttons, labels, textboxes, and so on. Following is
a simple example of XML file having LinearLayout −
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
android:layout_width="wrap_content"
android:layout_height="wrap_content"
<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
</LinearLayout>
Once your layout has created, you can load the layout resource from your application code, in
your Activity.onCreate() callback implementation as shown below −
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
1 Linear Layout
LinearLayout is a view group that aligns all children in a single direction,
vertically or horizontally.
2 Relative Layout
RelativeLayout is a view group that displays child views in relative positions.
3 Table Layout
TableLayout is a view that groups views into rows and columns.
4 Absolute Layout
AbsoluteLayout enables you to specify the exact location of its children.
5 Frame Layout
The FrameLayout is a placeholder on screen that you can use to display a single
view.
7 Grid View
GridView is a ViewGroup that displays items in a two-dimensional, scrollable
grid.
Layout Attributes:
Each layout has a set of attributes which define the visual properties of that layout. There
are few common attributes among all the layouts and there are other attributes which are specific
to that layout. Following are common attributes and will be applied to all the layouts:
1 android:id
This is the ID which uniquely identifies the view.
2 android:layout_width
This is the width of the layout.
3 android:layout_height
This is the height of the layout
4 android:layout_marginTop
This is the extra space on the top side of the layout.
5 android:layout_marginBottom
This is the extra space on the bottom side of the layout.
6 android:layout_marginLeft
This is the extra space on the left side of the layout.
7 android:layout_marginRight
This is the extra space on the right side of the layout.
8 android:layout_gravity
This specifies how child Views are positioned.
9 android:layout_weight
This specifies how much of the extra space in the layout should be allocated to the View.
10 android:layout_x
This specifies the x-coordinate of the layout.
11 android:layout_y
This specifies the y-coordinate of the layout.
12 android:layout_width
This is the width of the layout.
13 android:layout_width
This is the width of the layout.
14 android:paddingLeft
This is the left padding filled for the layout.
16 android:paddingTop
This is the top padding filled for the layout.
17 android:paddingBottom
This is the bottom padding filled for the layout.
Here width and height are the dimension of the layout/view which can be specified in terms of dp
(Density-independent Pixels), sp ( Scale-independent Pixels), pt ( Points which is 1/72 of an inch),
px( Pixels), mm ( Millimeters) and finally in (inches).
You can specify width and height with exact measurements but more often, you will use one of
these constants to set the width or height −
Gravity attribute plays important role in positioning the view object and it can take one or more
(separated by '|') of the following constant values.
top 0x30 Push object to the top of its container, not changing its
size.
bottom 0x50 Push object to the bottom of its container, not changing
its size.
left 0x03 Push object to the left of its container, not changing its
size.
right 0x05 Push object to the right of its container, not changing its
size.
center_vertical 0x10 Place object in the vertical center of its container, not
changing its size.
center_horizontal 0x01 Place object in the horizontal center of its container, not
changing its size.
center 0x11 Place the object in the center of its container in both the
vertical and horizontal axis, not changing its size.
clip_vertical 0x80 Additional option that can be set to have the top and/or
bottom edges of the child clipped to its container's
bounds. The clip will be based on the vertical gravity: a
top gravity will clip the bottom edge, a bottom gravity
will clip the top edge, and neither will clip both edges.
clip_horizontal 0x08 Additional option that can be set to have the left and/or
right edges of the child clipped to its container's bounds.
The clip will be based on the horizontal gravity: a left
gravity will clip the right edge, a right gravity will clip
the left edge, and neither will clip both edges.
end 0x00800005 Push object to the end of its container, not changing its
size.
View Identification:
A view object may have a unique ID assigned to it which will identify the View uniquely within
the tree. The syntax for an ID, inside an XML tag is −
android:id="@+id/my_button"
The at-symbol (@) at the beginning of the string indicates that the XML parser should
parse and expand the rest of the ID string and identify it as an ID resource.
The plus-symbol (+) means that this is a new resource name that must be created and
added to our resources. To create an instance of the view object and capture it from the
layout, use the following −
Linear Layout:
Linear Layout is a simple layout used in android for layout designing. In the Linear layout
all the elements are displayed in linear fashion means all the childs/elements of a linear layout are
displayed according to its orientation. The value for orientation property can be either
horizontal or vertical.
1. Vertical
2. Horizontal
As the name specified these two orientations are used to arrange there child one after the other, in
a line, either vertically or horizontally. Let‟s we describe these in detail.
1. Vertical:
In this all the child are arranged vertically in a line one after the other. In below code snippets we
have specified orientation “vertical” so the childs/views of this layout are displayed vertically.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1"
android:id="@+id/button"
android:background="#358a32" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button2"
android:id="@+id/button2"
android:background="#0058b6" />
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1"
android:id="@+id/button"
android:background="#358a32" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button2"
android:id="@+id/button2"
android:background="#0058b6" />
</LinearLayout>
1. Orientation: The orientation attribute used to set the childs/views horizontally or vertically.
In Linear layout default orientation is vertical.
android:layout_width="fill_parent"
android:layout_height="wrap_content"
</LinearLayout>
android:layout_width="fill_parent"
android:layout_height="wrap_content"
</LinearLayout>
2. Gravity: The gravity attribute is an optional attribute which is used to control the alignment
of the layout like left, right, center, top, bottom etc.
Example: We have set gravity right for linear layout. So the buttons gets align from right
side in Horizontal orientation.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="right"
android:orientation="horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/button2"
android:background="#0e7d0d" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Button1"
android:id="@+id/button"
android:background="#761212" />
</LinearLayout>
3. Layout_weight: The layout weight attribute specify each child control‟s relative importance
within the parent linear layout.
Example: weight property for button in linear layout. In the below example one button is of
weight 2 and other is of weight 1.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Weight 2"
android:background="#761212"
MOBILE APPLICATION DEVELOPMENT 59
android:layout_margin="5dp"
android:id="@+id/button"
android:layout_weight="2" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#761212"
android:layout_margin="5dp"
android:layout_weight="1"
</LinearLayout>
In the layout image you can notice Button with weight 2 gets more size related the other.
4. Weight Sum: WeightSum is the sum up of all the child attributes weight. This attribute is
required if we define weight property of the childs.
Example: In the same above example of weight, we can define weightSum value 3.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="3"
android:orientation="horizontal">
</LinearLayout>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textView"
android:layout_gravity="center_horizontal" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 1"
android:background="#009300" />
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 2"
android:background="#e6cf00" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 3"
android:background="#0472f9" />
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 4"
android:background="#e100d5" />
</LinearLayout>
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textView"
android:layout_gravity="center_horizontal"
android:layout_weight="0"/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 1"
android:background="#009300"
android:layout_weight="1"/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 2"
android:background="#e6cf00"
android:layout_weight="1"/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 3"
android:background="#0472f9"
android:layout_weight="1"/>
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="Button 4"
android:background="#e100d5"
android:layout_weight="1"/>
</LinearLayout>
Relative Layout:
The Relative Layout is very flexible layout used in android for custom layout designing. It gives
us the flexibility to position our component/view based on the relative or sibling component‟s
position. Just because it allows us to position the component anywhere we want so it is considered
as most flexible layout. For the same reason Relative layout is the most used layout after
the Linear Layout in Android. It allow its child view to position relative to each other or relative
to the container or another container.
In Relative Layout, you can use “above, below, left and right” to arrange the component‟s
position in relation to other component.
For example, suppose a view with id textview2 is what we want to place above another view with
id textview. Below is the code and layout image.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="Text2"
android:id="@+id/textView2"
android:layout_above="@+id/textView"
android:layout_marginBottom="100dp"
android:layout_centerHorizontal="true"/>
2. AlignBottom: AlignBottom is used to makes the bottom edges of the view match the bottom
edge of the given anchor view ID and it must be a reference to another resource, in the form of id.
Example: android:layout_ alignBottom =”@+id/button1″
In the below example we have aligned a view with id textView2 Bottom of another view with id
textView. Below is the coded and layout image.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_centerHorizontal="true"
android:id="@+id/textView2"
android:layout_alignBottom="@+id/textView"
android:layout_marginBottom="90dp"
/>
3. AlignLeft: AlignLeft is used to make the left edge of the view match the left edge of the given
anchor view ID and must be a reference to another resource, in the form of Example:
android:layout_ alignLeft =”@+id/button1″.
Below is the code and layout image in which we have aligned a view with id textView2 left of
another view with id textView.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textView2"
android:layout_alignLeft="@+id/textView"
android:layout_below="@+id/textView"
4. AlignRight: AlignRight property is used to make the right edge of this view match the right
edge of the given anchor view ID and must be a reference to another resource, in the form like this
example: android:layout_alignRight=”@+id/button1″
Below is the code and layout image in which we have aligned a view with id textView2 right of
another view with id textView.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textView2"
android:layout_alignRight="@+id/textView"
android:layout_below="@+id/textView"
android:layout_marginTop="20dp"/>
5.AlignStart: AlignStart property is used to makes the start edge of this view match the start edge
of the given anchor view ID and must be a reference to another resource, in the form of like this
example: android:layout_alignStart=”@+id/button1″
Below is the alignStart code and layout image in which we have aligned a view with id textView2
start of another view with id textView.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_alignStart="@+id/textView"
/>
6. AlignTop: AlignTop property is used to makes the top edge of this view match the top edge of
the given anchor view ID and must be a reference to another resource, in the form like this
example: android:layout_alignTop=”@+id/button1″.
Below is the alignTop code and layout image in which we have aligned a view with id textView
Top of another image with id imageView.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textView"
android:layout_alignTop="@+id/imageView"
/>
Below is the alignParentBottom code and layout image in which textView is simply displayed
using the alignParentBottom.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textView"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:layout_marginBottom="120dp" />
8. AlignParentEnd: If alignParentEnd property is true, then it makes the end edge of this view
match the end edge of the parent. The value of align parent End is either true or false. Example:
android:layout_alignParentEnd=”true”.
In alignParentEnd the bottom edge of the view matches the bottom edge of the parent.
Below is the alignParentEnd code and layout image in which textView is simply displayed on
Image in the end.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textView"
android:layout_alignBottom="@+id/imageView"
android:layout_alignParentEnd="true"
/>
MOBILE APPLICATION DEVELOPMENT 69
9. AlignParentLeft: If alignParentLeft property is true, makes the left edge of this view match the
left edge of the parent. The value of align parent left is either true or false. Example:
android:layout_alignParentLeft=”true”.
AlignParentLeft and alignLeft are two different properties. In alignLeft we give the
reference of another view in the form of id that the view is aligned to the left of the referenced
view but in alignParentLeft the left edge of the view matches the left edge of the parent.
Below is the alignParentLeft example code and layout image in which textView is simply
displayed on parent Image in the left side.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textView"
android:layout_alignBottom="@+id/imageView"
android:layout_alignParentLeft="true"
/>
Important Note: alignParentRight and alignRight are two different properties. In alignRight we
give the reference of another view in the form of id that the view is aligned to the right of the
referenced view but in alignParentRight the right edge of the view matches the right edge of the
parent.
Below is the alignParentRight example code and layout image in which textView is simply
displayed on parent Image in the right side.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textView"
android:layout_alignBottom="@+id/imageView"
android:layout_alignParentRight="true"
/>
11. AlignParentStart: If alignParentStart is true, then it makes the start edge of this view match
the start edge of the parent. The value of align parent start is either true or false. Example:
android:layout_alignParentStart=”true”.
AlignParentStart and alignStart are two different properties, In alignStart we give the
reference of another view in the form of id that the view is aligned at the start of referenced view
but in alignParentStart the start edge of the view matches the start edge of the
parent(RelativeLayout).
Below is the alignParentStart example code and layout image in which textView is simply
displayed on parent Image in the right side.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:id="@+id/textView"
android:layout_alignTop="@+id/imageView"
android:layout_alignParentStart="true"
/>
12. AlignParentTop: If alignParentTop is true, then it makes the top edge of this view match the
top edge of the parent. The value of align parent Top is either true or false. Example:
android:layout_alignParenTop=”true”.
AlignParentTop and alignTop are two different properties, In alignTop we give the
reference of another view in the form of id that the view is aligned to the top of the referenced
view but in alignParentTop the top edge of the view matches the top edge of the
parent(RelativeLayout).
Below is the example code of alignParentTop property and also layout image.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:textSize="20sp"
android:textColor="#000"/>
13. CenterInParent: If center in parent is true, makes the view in the center of the screen
vertically and horizontally. The value of center in parent is either true or false. Example:
android:layout_centerInParent=”true”.
Below is the example code of centerInParent property and also layout image.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:textSize="20sp"
android:textColor="#000"
/>
14. CenterHorizontal: If centerHorizontal property is true, makes the view horizontally center.
The value of centerHorizontal is either true or false.Example: android:layout_centerHorizontal
=”true”.
Below is the example code of centerHorizontal property and also layout image.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text1 center Horizontal"
android:layout_centerHorizontal="true"
android:textSize="20sp"
android:textColor="#000"
/>
15. CenterVertical: If centerVertical property is true, make the view vertically center. The value
of align parent bottom is either true or false. Example: android:layout_centerVertical=”true”.
Below is the example code of centerVertical property and also layout image.
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Text1 center vertical"
android:layout_centerVertical="true"
android:textSize="20sp"
android:textColor="#000"
/>
Example 1: Here we are designing a simple log in screen in Android Studio using Relative
Layout. Below is the final output:
Below is the code of activity_main.xml for designing UI with explanation included in it:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceLarge"
android:text="SIGN IN"
android:id="@+id/textView3"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true" />
<TextView
android:id="@+id/userName"
MOBILE APPLICATION DEVELOPMENT 75
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="@dimen/activity_horizontal_margin"
android:layout_marginTop="110dp"
android:text="UserName:"
android:textColor="#000000"
android:textSize="20sp" />
<TextView
android:id="@+id/password"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/userName"
android:layout_margin="@dimen/activity_horizontal_margin"
android:text="Password:"
android:textColor="#000000"
android:textSize="20sp" />
<EditText
android:id="@+id/edt_userName"
android:layout_width="fill_parent"
android:layout_height="40dp"
android:layout_marginLeft="@dimen/activity_horizontal_margin"
android:layout_marginTop="100dp"
<EditText
android:layout_width="fill_parent"
android:layout_height="40dp"
android:layout_below="@+id/edt_userName"
android:layout_centerVertical="true"
android:layout_toRightOf="@+id/password"
android:hint="Password" />
<Button
android:id="@+id/btnLogin"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/password"
android:layout_centerHorizontal="true"
android:layout_marginTop="20dp"
android:background="#03B424"
android:text="Login"
android:textColor="#ffffff"
android:textStyle="bold" />
</RelativeLayout>
Absolute Layout:
an Absolute Layout is a layout used to design the custom layouts. In this layout you can specify
the exact location of its children by using x and y coordinates.
Absolute layout are harder to maintain for different mobile screen sizes than other types of layouts
because we set the exact location of a child view or called component. The positioning is based on
x(top) and y(left) coordinates and that positioning is not as useful in world of various screen
resolutions(sizes) and aspect ratios.
Absolute layout is depreciated in Android because of the same reason as discussed in above note.
android:layout_width="fill_parent"
android:layout_height="fill_parent">
</AbsoluteLayout>
android:id="@+id/absoluteLayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
2. Layout_x: In Absolute Layout layout_x attribute is used to specify the x- coordinate of the
view(TextView or any other view). The possible value for this is in dp or px.
Below is the layout_x attribute‟s example code with explanation included in which we set the
200px value for the x-coordinate.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="AbhiAndroid"
android:textSize="25sp"
Below is the layout_y attribute‟s example code with explanation included in which we set the
200px value for the y- coordinate.
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textSize="25sp"
Select File -> New -> New Project. Fill the forms and click “Finish” button.
Step 2: Open res -> layout -> activity_main.xml (or) main.xml and add following code. Here we
are designing a login form inside Absolute Layout.
<AbsoluteLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
android:layout_x="110px"
android:layout_y="110px"
android:text="User Name"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:layout_y="80px"
android:width="100px"
android:layout_width="200dp"
android:layout_height="wrap_content" />
<TextView
android:layout_x="110px"
android:layout_y="200px"
android:text="Password"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<EditText
android:layout_x="250px"
android:layout_y="150px"
android:width="100px"
android:layout_width="200dp"
android:layout_height="wrap_content" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Log In"
android:layout_x="300px"
android:layout_y="300px"/>
</AbsoluteLayout>
Step 3: Now Open java -> package -> MainActivity.java and paste the below code.
package example.abhiandriod.absolytelayoutexample
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MenuItem;
@Override
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
@Override
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.menu_main, menu);
return true;
@Override
// Handle action bar item clicks here. The action bar will
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
return super.onOptionsItemSelected(item);
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="example.abhiandriod.absolytelayoutexample" >
<application
android:allowBackup="true"
android:icon="@mipmap/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
android:name=".MainActivity"
android:label="@string/app_name" >
<intent-filter>
</intent-filter>
</activity>
</application>
</manifest>
Step 5: Lastly Open res -> values ->strings.xml and paste the below code.
<resources>
<string name="app_name">AbsolyteLayoutExample</string>
<string name="action_settings">Settings</string>
</resources>
Now run the App in Emulator or AVD. You will see the login form designed in Absoulte Layout
having fix x and y coordinate.
Try opening the same layout in different size Emulator and you will see it doesn‟t fit in different
size device. That‟s why Android has depreciated the use of Absolute Layout.
Let‟s we take an example of scale type to understand the actual working of scale type in a image
view.
In below example code we set the value for scale type “fitStart” which is used to fit the image in
the start of the image view as shown below:
<ImageView
android:id="@+id/simpleImageView"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:src="@drawable/lion"
android:scaleType="fitStart"/>
<!--set scale type fit start of image view-->
Step 3: Now open res -> layout -> activity_main.xml (or) main.xml and add following code:
In this step we add the code for displaying an image view on the screen in a relative layout. Here
make sure you have already saved two images name lion and monkey in your drawable folder.
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
Step 4: Now open app -> java -> package -> MainActivity.java and add the following code:
In this step we add the code to initiate the image view‟s and then perform click event on them.
package example.abhiandriod.imageviewexample;
import android.graphics.Color;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ImageView simpleImageViewLion = (ImageView) findViewById(R.id.simpleImageView
Lion); //get the id of first image view
ImageView simpleImageViewMonkey = (ImageView) findViewById(R.id.simpleImage
ViewMonkey);//get the id of second image view
simpleImageViewLion.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Toast.makeText(getApplicationContext(), "Lion", Toast.LENGTH_LONG).show();
//display the text on image click event
}
});
simpleImageViewMonkey.setOnClickListener(new View.OnClickListener() {
}
Output:
AVD in Emulator and run the App. You will see the images of Lion and Monkey displayed on
screen. Click on any Animal image and his name will appear on Screen. We clicked on Lion.
Frame Layout:
Frame Layout is one of the simplest layout to organize view controls. They are designed to
block an area on the screen. Frame Layout should be used to hold child view, because it can be
difficult to display single views at a specific area on the screen without overlapping each other.
We can add multiple children to a Frame Layout and control their position by assigning gravity to
each child, using the android:layout_gravity attribute.
<ImageView
android:layout_width="200dp"
android:layout_height="200dp"
android:layout_marginBottom="10dp"
android:src="@mipmap/ic_launcher"
android:scaleType="centerCrop"
/>
<!--Textview will not be shown because of foreground color is drawn over it-->
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="center_horizontal"
android:text="abhiAndroid"/>
</LinearLayout>
</FrameLayout>
5. android:measureAllChildren
This determines whether to measure all children including gone state visibility or just those which
are in the visible or invisible state of measuring visibility. The default value of measureallchildren
is false. We can set values in the form of Boolean i.e. “true” OR “false”.
This may also be a reference to a resource (in the form “@[package:]type:name“) or theme
attribute (in the form “?[package:][type:]name“) containing a value of this type.
If measuresAllChildren is set true then it will show actual width and height of frame layout even if
the views visibility is in gone state.
Examples of Frame layout having measuresAllChildren attribute:
In the below code the ImageView visibility is set gone and measuresAllChildren is set true. The
output will show actual height and width the Frame Layout despite visibility is set gone. We have
used Toast to display the height and width:
MOBILE APPLICATION DEVELOPMENT 92
Below is the Code of activity_main.xml
Make sure you have image in Drawable folder. In our case we have used ic_launcher image which
we added in Drawable.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/frame"
android:orientation="vertical" android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:measureAllChildren="true"
>
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:visibility="gone"
android:src="@drawable/ic_launcher"/>
</FrameLayout>
Below is the code of MainActivity.java . Here we have used Toast to display height and width
on screen.
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.demo);
FrameLayout frame=(FrameLayout)findViewById(R.id.frame);
frame.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED);
int width = frame.getMeasuredWidth();
int height = frame.getMeasuredHeight();
Toast.makeText(getApplicationContext(),"width="+width+"
height="+height,Toast.LENGTH_SHORT).show();
}
}
When you run the App in Emulator you will see the below output:
Step 1: Create a new project in Android Studio and name it FrameTesting. (Select File -> New -
> New Project. Fill the forms and click “Finish” button)
Step 2: Now Open res -> layout -> activity_main.xml and add the following code. Here we are
putting different TextView in Frame Layout.
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_height="match_parent"
android:layout_width="match_parent"
>
<TextView android:text="LeftTop"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="RightTop"
android:layout_gravity="top|right" />
<TextView android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:text="CentreTop"
android:layout_gravity="top|center_horizontal" />
<TextView android:text="Left"
android:layout_gravity="left|center_vertical"
android:layout_width="wrap_content"
Step 1: Create a new project in Android Studio. In our case we created FrameLayoutJAVA.
Step 2: Just add the following code to your MainActivity.java . Explanation is included in the
code as comments.
package abhiandroid.com.farmelayoutjava;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Bundle;
import android.app.Activity;
import android.view.Gravity;
import android.view.Menu;
import android.widget.AbsListView;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
3. Shrink Columns: Shrink column attribute is used to shrink or reduce the width of the
column„s. We can specify either a single column or a comma delimited list of column numbers for
this attribute. The content in the specified columns word-wraps to reduce their width. If the value
is 0 then the first column‟s width shrinks or reduces by word wrapping its content. If the value is
0,1 then both first and second columns are shrinks or reduced by word wrapping its content. If the
value is „*‟ then the content of all columns is word wrapped to shrink their widths.
Below is the example code of shrink column attribute of table layout with explanation included in
which we shrink the first column of layout.
<?xml version="1.0" encoding="utf-8"?>
<TableLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:shrinkColumns="0"> <!-- shrink the first column of the layout-->
<!-- first row of the table layout-->
<TableRow
android:id="@+id/firstRow"
android:layout_width="fill_parent"
android:layout_height="wrap_content">
<!-- first element of the first row-->
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#b0b0b0"
android:padding="18dip"
android:text="Shrink Column Example"
android:textColor="#000"
android:textSize="18dp" />
</TableRow>
</TableLayout>
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// initiate a button
Button loginButton = (Button) findViewById(R.id.loginBtn);
// perform click event on the button
loginButton.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Toast.makeText(getApplicationContext(), "Hello AbhiAndroid..!!!",
Toast.LENGTH_LONG).show(); // display a toast message
}
});
}
}
Step 4: Open res -> values -> strings.xml
In this step we open string file which is used to store string data of the app.
<resources>
<string name="app_name">TableLayoutExample</string>
<string name="hello_world">Hello world!</string>
<string name="action_settings">Settings</string>
<string name="loginForm">Login Form</string>
<string name="userName">UserName</string>
<string name="password">Password</string>
<string name="login">LogIn</string>
</resources>
Output:
Now run the App and you will see the Login form UI which we designed in Table Layout.
import android.app.Activity;
import android.os.Bundle;
Figure 3.16. (left) Controls in portrait mode, and (right) the controls in landscapemode
Figure 3.17. (left) Controls in portrait mode, and (right) some controls disappear
in landscape mode.
To use the blank space on the right side of the screen in landscape mode, we need to define
another layout file, activity_screen_orientation_app.xml, created in the res/layout-land folder.
The layout-land folder has to be created manually inside the res folder. Right-click on
the resfolder in the Package Explorer window and select the New, Folder option. A dialog box
opens, asking for the name for the new folder. Assign the name layout-land to the new folder, and
click the Finish button. Copy the activity_screen_orientation_app.xml file from
the res/layoutfolder and paste it into res/layout-land folder. Modify
the activity_screen_orientation_app.xml file in the res/layout-land folder so as to arrange the
controls in landscape mode.
Listing 3.18. The Layout File activity_screen_orientation_app.xml in the res/layout-
landFolder
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<Button
android:id="@+id/Apple"
android:text="Apple"
android:layout_width="250dp"
android:layout_height="wrap_content"
android:padding="20dip"
android:layout_marginTop="20dip" />
<Button
android:id="@+id/Mango"
android:text="Mango"
Figure 3.18. (left) Controls in portrait mode, and (right) all controls are visible
in landscape mode.
The res folder showing the nested drawable (drawable-hdpi, drawable-ldpi, drawable-mdpi)
layouts and values folders and their content
Types of Resources:
A brief outline of the three folders is provided here:
• drawable folder—Depending on the target platform chosen, our application can have either a
single directory, drawable, or four directories, drawable-ldpi, drawable-mdpi, drawable-hdpi,
and drawable-xhdpi, where we can store the images used in our application. If our application has
a single directory, drawable, then the images to be used in our application, regardless of
resolution, are stored in it. If our application has four directories, then the images with different
screen resolutions are stored in the respective directories. That is, the images of low, medium,
high, and extra high resolutions are stored in the drawable-ldpi, drawable-mdpi, drawable-hdpi,
and drawable-xhdpi directories, respectively. Android chooses the image(s) from the respective
directory, depending on the density of the device used to run the application.
• layout folder—This folder contains a layout file automatically created for us. The default name
assigned to this file is activity_main.xml, but we can assign any name to it. We saw how to use
this file to lay out Views in the desired format.
• menu folder—This folder contains XML file(s) that represent application menus. Again, the
default name assigned to the menu file that is automatically created for us is activity_main.xml,
but we can change the name if we want.
• values folder—This folder by default contains a strings.xml file that we can use to define values
resources that include strings, colors, dimensions, styles, and string or integer arrays. We can also
create individual XML files for each of these resources instead. The folder also contains
When our application is built, all resources are compiled and included in our application package.
On compilation, an R class file is created that contains references to all the resources created and
hence enables us to reference them in the Java code. For each of the resource types, the R
class contains static subclasses for string, drawable, and layout resource types. The subclasses
created are R.string, R.drawable, and R.layout, respectively. Through these subclasses, we can
access their associated resources in Java code.
The three TextViews displaying the text assigned to them via String resource and Java code
Let‟s change the size of the text in these TextView controls via dimension resources.
Dimension Resources:
Dimension resources are used for standardizing certain application measurements. These
resources can be used to specify the sizes for fonts, layouts, and widgets. Also, we can modify the
size of any control in the application without changing the code. Besides this, we can define
dimensions for different screen resolutions and densities to support different hardware.
To try out dimension resources, let‟s open the application ValuesResourcesApp and add an XML
file called dimens.xml to the values folder.
Code Written in the dimens.xml File:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<dimen name="small_size">15dp</dimen>
<dimen name="medium_size">15sp</dimen>
<dimen name="large_size">20pt</dimen>
</resources>
We can see that the dimension resource is defined throughthe dimen element.
The dimen element contains a numerical value followed by unit of measurement.
Like other resources, it includes the nameproperty to specify the ID of the resource.
We can use any of the following units of measurement:
• px—Pixels
• in—Inches
• mm—Millimeters
• pt—Points
MOBILE APPLICATION DEVELOPMENT 120
• dp—Density-independent pixels based on a 160-dpi (pixel density per inch) screen
• sp—Scale-independent pixels
In the strings.xml file, we have defined three dimension resources: 15dp, 15sp, and 20pt,
represented by the three resource IDs small_size, medium_size, and large_size, respectively. Let‟s
apply the dimension resources to our TextView controls name_view, address_view,
and message_view. First, we learn to apply dimension resources through the layout file followed
by Java code. To apply dimension resources to the TextView controls,
modify activity_values_resources_app.xml.
The Layout File activity_values_resources_app.xml on Applying Dimension Resources
to TextView Controls
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/name_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/str_name"
android:textSize="@dimen/small_size" />
<TextView
android:id="@+id/address_view"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<TextView
android:id="@+id/message_view"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/str_message"
android:textSize="@dimen/large_size" />
</LinearLayout>
In the preceding code block, the two statements access the two dimension
resources small_size and large_size and apply to the two TextViewswith the IDs name_view and
message_view, respectively.
Their text size is set to 15px and 20sp, respectively. Now let‟s see how to apply dimension
resources to a View via Java code.
android:textSize="@dimen/small_size"
and
android:textSize="@dimen/large_size"
To apply the dimension resource medium_size to our TextView address_view, add these
statements to the Java file ValuesResourcesAppActivity.java:
float addressSize= this.getResources().getDimension(R.dimen.medium_size);
addressView.setTextSize(addressSize);
The TextView to which we want to apply the dimension resource is accessed from the layout file
and mapped to the TextView object addressView. Thereafter, we access our Resources object by
calling there the get Resource() method on our activity object.
The three TextViews displayed in different colors applied via the Color Resource.
The TextView controls are distinguished through different sizes.
Styles and Themes:
A style is a collection of attributes such as color, font, margin, and padding that we can apply
collectively to our Views, Activity, or an entire application. That is, instead of applying attributes
individually to the components of our application, we can create a style incorporating all these
attributes and quickly apply it instead. Through styles, we can apply a consistent dynamic look to
our Views, Activity, and to the overall application. Also, we can easily change the appearance of
our Views and application by simply specifying a different style or modifying the properties of the
existing style, all without disturbing the Java code.
A style is created by using a style element with one or more item child elements.
The style element includes a name property to specify the resource ID. Each item element
includes a name property to define the attributes such as color, font, and so on. An item element
defines an attribute and its value shown in this syntax:
<resources>
<style name="resource_ID">
<item name="attribute_name">value </item>
</style>
</resources>
Styles support inheritance; that is, the attributes of any existing style can be accessed and included
in the current style by using the parent property of the style element. For example, the attributes
defined in a style named style1 can be included in the style named style2 by making use of
the parent property in style2 as shown here:
<style name="style2" parent="style1" >
To apply styles to the individual Views in the layout file, open the styles.xml file that already
exists in the values folder. In the styles.xml file, define the styles.
<ToggleButton
android:id="@+id/tb1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:text="ToggleButton 1"
android:textOff="Off"
android:textOn="On" />
<ToggleButton
android:id="@+id/tb2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBaseline="@+id/tb1"
android:layout_alignBottom="@+id/tb1"
android:layout_toRightOf="@+id/tb1"
android:text="ToggleButton 2"
android:textOff="Off"
android:textOn="On" />
<android.support.v7.widget.SwitchCompat
android:id="@+id/switchButton"
android:layout_width="wrap_content"
android:layout_centerInParent="true"
android:checked="false"
android:layout_height="wrap_content"
android:textAppearance="?android:attr/textAppearanceMedium"
android:text="Switch example"/>
</RelativeLayout>
3. setImageResource(int resid): This method is also used to set an image in image switcher. The
image is passed in the form of integer id.
Below we set image in ImageSwitcher by using setImageDrawable method.
ImageSwitcher simpleImageSwitcher=(ImageSwitcher)findViewById(R.id.
simpleImageSwitcher); // initiate a ImageSwitcher
simpleImageSwitcher.setImageResource(R.drawable.ic_launcher); // set image resource in
ImageSwitcher
4. setImageURI(Uri uri): This method is also used to set an image in image switcher. The image
is passed in the form of URI.
Below we set Image in ImageSwitcher from raw folder using Uri:
Before using below code first create a raw name folder in res directory and save an image name
image1 in that folder.
ImageSwitcher simpleImageSwitcher=(ImageSwitcher)findViewById(R.id. simpleImage
Switcher); // get reference of ImageSwitcher
simpleImageSwitcher.setImageURI(Uri.parse("android.resource://" + getPackageName() + "/" +
R.raw.image1)); // set Image in ImageSwitcher from raw folder using Uri
5. loadAnimation(Context context, int id): This method is used whenever we need to define an
object of Animation class through AnimationUtils class by calling a static method loadAnimation.
Below we create an object of Animation class and load an animation by using AnimationUtils
class.
// load an animation by using AnimationUtils class
Animation in = AnimationUtils.loadAnimation(this, android.R.anim.slide_in_left);
Animation out = AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right);
<ImageSwitcher
android:id="@+id/simpleImageSwitcher"
android:layout_width="match_parent"
android:layout_height="200dp"
android:layout_gravity="center_horizontal"
android:layout_marginTop="50dp" />
<Button
android:id="@+id/buttonNext"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="150dp"
MOBILE APPLICATION DEVELOPMENT 140
android:layout_gravity="center"
android:background="#050"
android:textColor="#fff"
android:textStyle="bold"
android:text="NEXT" />
</LinearLayout>
Step 3: Open src -> package -> MainActivity.java
In this step we open MainActivity and add the code for initiate the ImageSwitcher and Button. In
this Firstly we create an array of id‟s Images and create dynamic ImageView using setFactory
method and then load and set slide in left and slide in right animation and finally set the Image in
the ImageSwitcher on button click using setImageResource method. Whenever a user click on
next button ImageSwitcher switch between the images and the current Image will go OUT and
next Image will come in with specified animation.
package com.example.ip_d.imageswitcherexample;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.ImageSwitcher;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ViewSwitcher;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Declare in and out animations and load them using AnimationUtils class
Animation in = AnimationUtils.loadAnimation(this, android.R.anim.slide_in_left);
Animation out = AnimationUtils.loadAnimation(this, android.R.anim.slide_out_right);