Unit 3

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 43

Unit 3

UI Components & Layouts


Components of Android application
There are following four main components that can be used within an Android application −

Sr.No Components & Description

Activities
1
They dictate the UI and handle the user interaction to the smart phone screen.

Services
2
They handle background processing associated with an application.

Broadcast Receivers
3
They handle communication between Android OS and applications.

Content Providers
4
They handle data and database management issues.
Activities
• An activity represents a single screen with a user interface,in-short Activity performs
actions on the screen.
• For example, an email application might have one activity that shows a list of new
emails, another activity to compose an email, and another activity for reading
emails.
• If an application has more than one activity, then one of them should be marked as
the activity that is presented when the application is launched.
• An activity is implemented as a subclass of Activity class as follows −

public class MainActivity extends Activity


{
}
Services
• A service is a component that runs in the background to perform long-
running operations.
• For example, a service might play music in the background while the user is
in a different application, or it might fetch data over the network without
blocking user interaction with an activity.
• A service is implemented as a subclass of Service class as follows −

public class MyService extends Service


{
}
Broadcast Receivers
• Broadcast Receivers simply respond to broadcast messages from other applications
or from the system.
• For example, applications can also initiate broadcasts to let other applications know
that some data has been downloaded to the device and is available for them to use,
so this is broadcast receiver who will intercept this communication and will initiate
appropriate action.
• A broadcast receiver is implemented as a subclass of BroadcastReceiver class and
each message is broadcaster as an Intent object.
public class MyReceiver extends BroadcastReceiver
{
public void onReceive(context,intent) {}
}
Content Providers
• A content provider component supplies data from one application to others on
request.
• Such requests are handled by the methods of the ContentResolver class.
• The data may be stored in the file system, the database or somewhere else entirely.
• A content provider is implemented as a subclass of ContentProvider class and must
implement a standard set of APIs that enable other applications to perform
transactions.
public class MyContentProvider extends ContentProvider
{
public void onCreate(){}
}
Additional Components
There are additional components which will be used in the construction of above mentioned entities, their
logic, and wiring between them. These components are −
Sr.No. Components & Description

Fragments
1 Represents a portion of user interface in an Activity.

Views
2 UI elements that are drawn on-screen including buttons, lists forms etc.

Layouts
3 View hierarchies that control screen format and appearance of the views.

Intents
4 Messages wiring components together.

Resources
5 External elements, such as strings, constants and drawable pictures.

Manifest
6 Configuration file for the application.
Directory Structure of Android Application
Sr.No. Folder, File & Description
Java

1 This contains the .java source files for your project. By default, it includes an MainActivity.java source file having
an activity class that runs when your app is launched using the app icon.

res/drawable-hdpi
2
This is a directory for drawable objects that are designed for high-density screens.
res/layout
3
This is a directory for files that define your app's user interface.
res/values
4 This is a directory for other various XML files that contain a collection of resources, such as strings and colours
definitions.
AndroidManifest.xml
5 This is the manifest file which describes the fundamental characteristics of the app and defines each of its
components.
Build.gradle

6 This is an auto generated file which contains compileSdkVersion, buildToolsVersion, applicationId, minSdkVersion,
targetSdkVersion, versionCode and versionName
The Main Activity File

The main activity code is a Java file MainActivity.java. This is the actual application file which ultimately gets converted to a Dalvik
executable and runs your application. Following is the default code generated by the application wizard for Hello World! application

package com.example.helloworld;

import android.support.v7.app.AppCompatActivity;

import android.os.Bundle;

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_main);

Here, R.layout.activity_main refers to the activity_main.xml file located in the res/layout folder. The onCreate() method is one of
many methods that are figured when an activity is loaded.
The Manifest File

Whatever component you develop as a part of your application, you must declare all its components in a manifest.xml which resides at the root of the application project
directory. This file works as an interface between Android OS and your application, so if you do not declare your component in this file, then it will not be considered by the OS.
For example, a default manifest file will look like as following file −
<?xml version="1.0" encoding="utf-8"?>

<manifest xmlns:android="http://schemas.android.com/apk/res/android"

package="com.example.tutorialspoint7.myapplication">

<application

android:allowBackup="true"

android:icon="@mipmap/ic_launcher"

android:label="@string/app_name"

android:supportsRtl="true"

android:theme="@style/AppTheme">

<activity android:name=".MainActivity">

<intent-filter>

<action android:name="android.intent.action.MAIN" />

<category android:name="android.intent.category.LAUNCHER" />

</intent-filter>

</activity>

</application>

</manifest>
Here <application>...</application> tags enclosed the components related to the application. Attribute android:icon will point to
the application icon available under res/drawable-hdpi. The application uses the image named ic_launcher.png located in the
drawable folders

The <activity> tag is used to specify an activity and android:name attribute specifies the fully qualified class name of
the Activity subclass and the android:label attributes specifies a string to use as the label for the activity. You can specify
multiple activities using <activity> tags.

The action for the intent filter is named android.intent.action.MAIN to indicate that this activity serves as the entry point for the
application. The category for the intent-filter is named android.intent.category.LAUNCHER to indicate that the application can
be launched from the device's launcher icon.

The @string refers to the strings.xml file explained below. Hence, @string/app_name refers to the app_name string defined in
the strings.xml file, which is "HelloWorld". Similar way, other strings get populated in the application.

Following is the list of tags which you will use in your manifest file to specify different Android application components −

 <activity>elements for activities

 <service> elements for services

 <receiver> elements for broadcast receivers

 <provider> elements for content providers


The Strings File

The strings.xml file is located in the res/values folder and it contains all the text that your application uses. For example, the
names of buttons, labels, default text, and similar types of strings go into this file. This file is responsible for their textual
content. For example, a default strings file will look like as following file −
<resources>

<string name="app_name">HelloWorld</string>

<string name="hello_world">Hello world!</string>

<string name="menu_settings">Settings</string>

<string name="title_activity_main">MainActivity</string>

</resources>
The Layout File

The activity_main.xml is a layout file available in res/layout directory, that is referenced by your application when building
its interface. You will modify this file very frequently to change the layout of your application. For your "Hello World!"
application, this file will have following content related to default layout −
<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" >

<TextView

android:layout_width="wrap_content"

android:layout_height="wrap_content"

android:layout_centerHorizontal="true"

android:layout_centerVertical="true"

android:padding="@dimen/padding_medium"

android:text="@string/hello_world"

tools:context=".MainActivity" />

</RelativeLayout>
Android UI Controls
Sr. No. UI Control & Description
1 TextView
This control is used to display text to the user.

2 EditText
EditText is a predefined subclass of TextView that includes rich editing capabilities.

3 AutoCompleteTextView
The AutoCompleteTextView is a view that is similar to EditText, except that it shows a list of completion
suggestions automatically while the user is typing.

4 Button
A push-button that can be pressed, or clicked, by the user to perform an action.

5 ImageButton
An ImageButton is an AbsoluteLayout which enables you to specify the exact location of its children. This
shows a button with an image (instead of text) that can be pressed or clicked by the user.

6 CheckBox
An on/off switch that can be toggled by the user. You should use check box when presenting users with a
group of selectable options that are not mutually exclusive.
Android UI Controls
7 ToggleButton
An on/off button with a light indicator.

8 RadioButton
The RadioButton has two states: either checked or unchecked.

9 RadioGroup
A RadioGroup is used to group together one or more RadioButtons.

10 ProgressBar
The ProgressBar view provides visual feedback about some ongoing tasks, such as when you are performing a
task in the background.

11 Spinner
A drop-down list that allows users to select one value from a set.

12 TimePicker
The TimePicker view enables users to select a time of the day, in either 24-hour mode or AM/PM mode.

13 DatePicker
The DatePicker view enables users to select a date of the day.
Create UI Controls
Input controls are the interactive components in your app's user interface. Android provides a wide variety of
controls you can use in your UI, such as buttons, text fields, seek bars, check box, zoom buttons, toggle buttons, and
many more.

The syntax for an ID, inside an XML tag is −


android:id="@+id/text_id"

To create a UI Control/View/Widget you will have to define a view/widget in the layout file and assign it a unique ID
as follows −
<?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:id="@+id/text_id"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="I am a TextView" />
</LinearLayout>
Android - UI 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.
There are number of Layouts provided by Android which you will use in almost all the Android applications to provide different
view, look and feel.

Sr.No Layout & Description


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.
6 List View
ListView is a view group that displays a list of scrollable items.
7 Grid View
GridView is a ViewGroup that displays items in a two-dimensional, scrollable grid.
Layout Attributes

Sr.No Attribute & Description


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.
Layout Attributes

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.
Layout Attributes

14 android:paddingLeft
This is the left padding filled for the layout.

15 android:paddingRight
This is the right 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.
1. Linear Layout

LinearLayout is a view group that aligns all children in a single direction, vertically or horizontally
Android LinearLayout is a view group that aligns all children in either vertically or horizontally.
LinearLayout Attributes
Sr. No. Attribute & Description
android:id This is the ID which uniquely identifies the layout.
1

android:baselineAligned This must be a boolean value, either "true" or "false" and prevents the layout from
2 aligning its children's baselines.

android:baselineAlignedChildIndex When a linear layout is part of another layout that is baseline aligned, it
3 can specify which of its children to baseline align.

android:divider This is drawable to use as a vertical divider between buttons. You use a color value, in the
4 form of "#rgb", "#argb", "#rrggbb", or "#aarrggbb".

android:gravity This specifies how an object should position its content, on both the X and Y axes. Possible
5 values are top, bottom, left, right, center, center_vertical, center_horizontal etc.

android:orientation This specifies the direction of arrangement and you will use "horizontal" for a row,
6 "vertical" for a column. The default is horizontal.

7 android:weightSum Sum up of child weight


Absolute Layout:-

An Absolute Layout lets you specify exact locations (x/y coordinates) of its children. Absolute layouts are less
flexible and harder to maintain than other types of layouts without absolute positioning.
AbsoluteLayout Attributes

Sr.No Attribute & Description


1 android:id
This is the ID which uniquely identifies the layout.

2 android:layout_x
This specifies the x-coordinate of the view.
3 android:layout_y
This specifies the y-coordinate of the view.
Table Layout:-

Android TableLayout going to be arranged groups of views into rows and columns. You will use the
<TableRow> element to build a row in the table. Each row has zero or more cells; each cell can hold one
View object.
TableLayout containers do not display border lines for their rows, columns, or cells.
TableLayout Attributes

Sr.No. Attribute & Description


1 android:id
This is the ID which uniquely identifies the layout.
2 android:collapseColumns
This specifies the zero-based index of the columns to collapse. The column indices must be separated by a comma: 1, 2,
5.
3 android:shrinkColumns
The zero-based index of the columns to shrink. The column indices must be separated by a comma: 1, 2, 5.

4 android:stretchColumns
The zero-based index of the columns to stretch. The column indices must be separated by a comma: 1, 2, 5.
Relative Layout:-
Android RelativeLayout enables you to specify how child views are
positioned relative to each other. The position of each view can be
specified as relative to sibling elements or relative to the parent.

RelativeLayout lets child views specify their position relative to the


parent view or to each other (specified by ID). So you can align two
elements by right border, or make one below another, centered in the
screen, centered left, and so on.
RelativeLayout Attributes

Sr.No. Attribute & Description


1 android:id
This is the ID which uniquely identifies the layout.

2 android:gravity
This specifies how an object should position its content, on both the X and Y axes. Possible values are
top, bottom, left, right, center, center_vertical, center_horizontal etc.

3 android:ignoreGravity
This indicates what view should not be affected by gravity.
Sr.No. Attribute & Description
1 android:layout_above
Positions the bottom edge of this view above the given anchor view ID and must be a reference to another resource, in the form
"@[+][package:]type:name"
2 android:layout_below
Positions the top edge of this view below the given anchor view ID and must be a reference to another resource, in the form "@[+]
[package:]type:name".
3 android:layout_alignBottom
Makes the bottom edge of this view match the bottom edge of the given anchor view ID and must be a reference to another
resource, in the form "@[+][package:]type:name".
4 android:layout_alignLeft
Makes the left edge of this view match the left edge of the given anchor view ID and must be a reference to another resource, in
the form "@[+][package:]type:name".
5 android:layout_alignParentBottom
If true, makes the bottom edge of this view match the bottom edge of the parent. Must be a boolean value, either "true" or "false".
6 android:layout_alignParentEnd
If true, makes the end edge of this view match the end edge of the parent. Must be a boolean value, either "true" or "false".
7 android:layout_alignParentLeft
If true, makes the left edge of this view match the left edge of the parent. Must be a boolean value, either "true" or "false".
8 android:layout_alignParentRight
If true, makes the right edge of this view match the right edge of the parent. Must be a boolean value, either "true" or "false".
8 android:layout_alignParentStart
If true, makes the start edge of this view match the start edge of the parent. Must be a boolean value, either "true" or "false".
9 android:layout_alignParentTop
If true, makes the top edge of this view match the top edge of the parent. Must be a boolean value, either "true" or "false".
10 android:layout_alignRight
Makes 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 "@[+][package:]type:name".
11 android:layout_alignStart
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 "@[+][package:]type:name".
12 android:layout_alignTop
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 "@[+][package:]type:name".
13 android:layout_centerHorizontal
If true, centers this child horizontally within its parent. Must be a boolean value, either "true" or "false".
15 android:layout_centerInParent
If true, centers this child horizontally and vertically within its parent. Must be a boolean value, either "true" or "false".
16 android:layout_centerVertical
If true, centers this child vertically within its parent. Must be a boolean value, either "true" or "false".
17 android:layout_toEndOf
Positions the start edge of this view to the end of the given anchor view ID and must be a reference to another resource, in the
form "@[+][package:]type:name".
18 android:layout_toLeftOf
Positions the right edge of this view to the left of the given anchor view ID and must be a reference to another resource, in the
form "@[+][package:]type:name".
19 android:layout_toRightOf
Positions the left edge of this view to the right of the given anchor view ID and must be a reference to another resource, in the
form "@[+][package:]type:name".
20 android:layout_toStartOf
Positions the end edge of this view to the start of the given anchor view ID and must be a reference to another resource, in the
form "@[+][package:]type:name".
Frame Layout:-
Frame Layout is designed to block out an area on the screen to display a single item. Generally, FrameLayout
should be used to hold a single child view, because it can be difficult to organize child views in a way that's
scalable to different screen sizes without the children overlapping each other.
You can, however, add multiple children to a FrameLayout and control their position within the FrameLayout by
assigning gravity to each child, using the android:layout_gravity attribute.
FrameLayout Attributes

Sr.No Attribute & Description


1 android:id
This is the ID which uniquely identifies the layout.
2 android:foreground
This defines the drawable to draw over the content and possible values may be a color value, in the form of
"#rgb", "#argb", "#rrggbb", or "#aarrggbb".

3 android:foregroundGravity
Defines the gravity to apply to the foreground drawable. The gravity defaults to fill. Possible values are top,
bottom, left, right, center, center_vertical, center_horizontal etc.

4 android:measureAllChildren
Determines whether to measure all children or just those in the VISIBLE or INVISIBLE state when measuring.
Defaults to false.
ListView
• ListView is used when you have to show items in a vertically scrolling list. Best
example of it is our device's Contact List. With ListView, user can easily browse the
information, while scrolling up and down. You can set divider between every item and
set its height and color as per your UI design.
• Inside a ListView, we can show list of Text items by using TextView, or pictures
using ImageView, or any other view or a combination of views.
• As ListView is generally used to display a large set of data, hence it is not feasible to
manually create list items for the complete data, hence Android provides us with
special Adapter classes which can be used to supply data from datasets to ListView.
Following are some of the main attributes that are most commonly used:

Attribute Description
android:divider Using this attribute we can specify a divider between List items. A drawable or any
color can be specified as a value for this attribute.

android:dividerHeight Used to specify height of the divider.

<ListView
android:id="@+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:divider="@android:color/black"
android:dividerHeight="1dp"/>
Grid View
• Android GridView shows items in two-dimensional scrolling grid (rows & columns) and the grid items
are not necessarily predetermined but they automatically inserted to the layout using a ListAdapter
• GridView just works like ListView, The only difference is that GridView is used to display grid of View
objects.

• The view objects can be a Text view, an Image view or a view group which has both an image and some
text. Best example for this view is phone gallery which shows images in a grid. We can set number of
columns to specific number and auto-fit the images into the columns.

• Vertical and horizontal spacing between every single items of gridView can be set by verticalSpacing
and horizontalSpacing.
<GridView
android:id="@+id/gridView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:verticalSpacing="2dp"
android:horizontalSpacing="2dp"
android:numColumns="2"/>
layout_alignParentTop
layout_alignParentBottom
layout_alignParentLeft
layout_alignParentRight
layout_centerVertical
Layout_centerHorizontal

You might also like