MAD Chapter 3

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

UI Components And Layouts

Components of Android Application

There are four main Android app components: 

Activities, Services, Content providers,
and Broadcast receivers.

 Whenever you create or use any of them, you must


include elements in the project manifest.

Application components are the essential building


blocks of an Android application.
Activities
 An activity represents a single screen with a user interface,
 Activity performs actions on the screen.
 An activity is the first stepping stone is building an
Android user application.
 It provides the space to the user for doing anything and
everything.
 For example, opening a contact, dialling a caller, etc.
everything is done by interacting with a window and window
is provided by an activity.
 A window is provided to each activity where user interfacing
is done.
 Generally, every Android application has more than one
activity.
There is one “main” activity. All other activities are child
activities.
There is a stack called back stack.
Whenever, there is a new window is started, previous
activity is pushed to the back stack and it is stopped until
the new activity is done.
 As soon as the back key of your device is pressed, new
activity is popped out of stack and destroyed. Now
previous activity resumes.

An activity is implemented as a subclass of Activity class
as follows −

public class MainActivity extends Activity {


}
Services
 Another important component of an android application is service.
 It does not provide user interface.
 It does long running operations in background.
 Service doesn’t terminate even if the component which initiated it got
terminated or switched to another application.
 For example, when you receive your email updates in inbox it is a
service.
 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
Android Application Structure
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/androi
d" 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>
This is an example of simple RelativeLayout 
 The TextView is an Android control used to build the
GUI and it have various attributes
like android:layout_width, android:layout_height etc
which are being used to set its width and height etc..
The @string refers to the strings.xml file located in the
res/values folder. Hence, @string/hello_world refers to
the hello string defined in the strings.xml file, which is
"Hello World!".
Android UI Controls
There are number of UI controls provided by Android that
allow you to build the graphical user interface for your app.
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, check box, zoom
buttons, toggle buttons, and many more.
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/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>
Then finally create an instance of the Control object and
capture it from the layout, use the following −
TextView myText = (TextView) findViewById(R.id.text_id);
Directory structure
The Project tool window has several views, including
the Android view, the Project view, and
the Packages view.

Each view shows the same stuff, but each view


organizes this stuff a bit differently.

The button just at above the left pane (shown by the


arrow) is used to open the selection box for choosing the
preferred method of viewing the file hierarchy.
By default, Android Studio will set the view
to Android.
The Project tool window provides a simple tree
interface with files and nested folders that you can
toggle.
When you create an application in Android Studio, you
find that the project is divided into an App folder and
Gradle scripts.
The App folder contains three subfolders
(manifests, java and res) that make up your
application.

They are divided so that it should be fairly easy to


determine which resources go in which folder.

If you expand all of the folders in the project


explorer you will see a vast array of files and
folders.

Most of them are managed by Android Studio.


1. Manifests folder
This is where you would put your manifest files.
 Most Android apps have single manifest file. But an
app may have several manifest files due to application
versioning, or for supporting specific hardware.
An  AndroidManifest.xml file is generated
inside manifest folder by Android Studio when you
create a project.
 This file contains the configuration parameters of the
project such as permissions, services and additional
libraries.
A manifest file also provides information to the OS and
Google Play store about your app.
2. Java folder
 This is the folder in your project where you will be
storing all of the source code files written in Java
programming language.

A MainActivity.java is automatically created in this


folder by Android Studio.

All of your classes will be available here, and


Android Studio will even bundle together the
package path so that you can work with the files
without having to drill down through the folders that
make up your package.
3. Res folder
It contains folders that help you separate and sort the resources
of your application.
 Resources basically mean all the needed files except the source
code.
 For example, while developing an app, you need to include
resource files such as the app-logo, photos, sounds, videos or
animations.
 Each file type should be added to its own folder to comply with
the Android development standards.
When you use Android Studio to create a new application, some
folders will be automatically generated for you.
 However, these folders are not the only ones you can use in
your project. The following are the folders that can be used
inside of the res folder:
3.1. Drawable folder
The drawable folder contains graphics that can be drawn to the screen.
e.g. images files (png, jpg and gif), various XML (clip drawable, insert
drawable, layer list, level list, scale drawable, shape draggable, state list,
transition drawable), and predetermined frame animations can be placed
here:
Bitmap file
Android supports bitmap files in three formats: .png (preferred), .jpg
(acceptable), .gif (discouraged).
Nine-Patch file
A PNG nine-patch file with stretchable regions to allow image resizing
based on content.
Layer list
An XML file that contains an array made up of other drawables.
State list
An XML file that is used for images that have multiple or different states of
appearance.
Level list
An XML file that is used to display other drawables that can be accessed based
on the level requested through setImageLevel().
Transition drawable
An XML file that contains a drawable that can be transitioned between two
items.
Inset drawable
An XML filethat is used to place one drawable inside the bounds of another
drawable.
Clip drawable
An XML file consisting of points that is used in conjunction with another
drawable to create a clipped objected.
Scale drawable
An XML file that contains a drawable that changes the dimension value of
another drawable based on its current value.
Shape drawable
An XML file that contains the values of geometric shape, color, size, and
similar attributes.
Layout folder
The layout folder contains XML files used for your
layouts.
These file are used to set up the layout for your Activity
and is used for basic alignment of your layouts,
components, and similar resources that are used for the
UI of your application.
activity_main.xml is automatically created in this folder
by Android Studio.
Layout folder may have multiple layout folders to handle
different devices.
This can be helpful when working with layouts that need
to be adjusted for devices with more or less screen
space available
Mipmap folder

The mipmap folder contains the launcher icon


files for the app.
A launcher icon is a graphic that represents your
app to users.
 The mipmap folder was introduced in Android
4.3.
Values folder
The values folder contains XML files that contain simple
values, such as strings, integers, and colors.
The values folder is used to keep track of the values you will
be using in your application.
To create applications with an easier maintenance cycle, it is
highly recommended to no longer hard-code values into your
code.
Instead, place values in XML files inside of the values folder.
 When you create a new project with Android Studio, the
following XML files will be generated automatically:
colors.xml
strings.xml
styles.xml
Other folders
Not all folders may be shown for your resources but you can create other folders for
other resources in your application. Following list describes each folder name as
well as what should be stored in that folder.
animator
XML files that define property animations.
anim
XML files that define tween animations.
color
XML files that define a state list of colors.
menu
XML files that define application menus.
raw
Any files to save in their raw form. For example, sound and video files are placed in
the raw folder.
xml
Any XML files that can be read at runtime.
font
Font files with extensions such as ttf, otf, or ttc, or XML files.
Gradle Scripts
APK(Android Application Package)files are built using the
gradle build system, which is integrated in the Android
Studio.
When we start an app, the gradle build scripts are
automatically created.
If you have special requirements for your project, you can
specify these requirements here.
The gradle scripts folder contains the scripts used to build
the app are: configuration files, properties files, and setting
files.
Components of screen
Fundamentals of UI Design
Every item in a user interface is a
subclass of Android View class which
is presentr inside the package
(android.view).
The android SDK provide set of pre-
buile views that can be used to
construct the user interface
Examples include items such as
button, imagebutton,checkbox,progress
Views
This class represents the basic building block for user
interface components.
A View 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 (buttons, text fields,
etc.). 
ViewGroup
The ViewGroup is a subclass of View and
provides invisible container that hold other
Views or other ViewGroups and define their
layout properties.
A Viewgroup provides the layout in which
we can order the appearance and sequence of
views.
Example of viewgroup ate
FrameLayout,LinearLayout etc
Fragments 

A Fragment represents a behaviour or a portion of user


interface in a FragmentActivity.
Introduced in android 3.0
A fragment has its own layout and its own behaviour
with its own life cycle callbacks.
You can add or remove fragments in an activity while
the activity is running.
You can combine multiple fragments in a single
activity to build a multi-pane UI.
A fragment can be used in multiple activities.
Activities
It dictate the UI and handle the user
interaction to the smart phone screen.
Activities represent the single screen
that user interact
Android - UI Layouts
A layout defines the structure for a user interface
in your app, such as in an activity.

All elements in the layout are built using a


hierarchy of View and ViewGroup objects.

 A View usually draws something the user can


see and interact with.

Whereas a View Group is an invisible container


that defines the layout structure for View and
other View Group objects
Illustration of a view hierarchy, which defines a UI
layout
The View objects are usually called "widgets" and can
be one of many subclasses, such
as Button or TextView.

 The ViewGroup objects are usually called "layouts"


can be one of many types that provide a different
layout structure, such
as LinearLayout or ConstraintLayout 
Linear Layout
LinearLayout is a view group that aligns all children in a
single direction, vertically or horizontally.
You can specify the layout direction with
the android:orientation attribute.
In LinearLayout, the child View instances arranged one by one,
so the horizontal list will have only one row of multiple columns
and vertical list will have one column of multiple rows.
LinearLayout Attributes
Example
Follow the following steps to modify the Android
application we created in Hello World
Following is the content of the modified main activity
file src/com.example.demo/MainActivity.java. This file
can include each of the fundamental lifecycle methods.
Following will be the content of res/layout/activity_main.xml file 
Following will be the content
of res/values/strings.xml to define two new constants

Now let's change the orientation of Layout as android:orientation="horizontal" and try
to run the same application, it will give following screen 
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
Example

 Follow the following steps to modify the Android application we created in Hello
World
Following is the content of the modified main activity
file src/com.example.demo/MainActivity.java. This file can include each of the
fundamental lifecycle methods.
Following will be the content of res/layout/activity_main.xml file −
Following will be the content of res/values/strings.xml to define two new constants

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 containers do not display border lines for their
rows, columns, or cells.
Example
This example will take you through simple steps to show how to create your own Android
application using Table Layout. Follow the following steps to modify the Android
application we created in Hello World
Following is the content of the modified main activity
file src/com.example.demo/MainActivity.java. This file can include each of the
fundamental lifecycle methods.
Following will be the content of res/layout/activity_main.xml file −
Following will be the content of res/values/strings.xml to define two new constants −
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 Attributes
Using RelativeLayout, you can align two elements by right
border, or make one below another, centered in the screen,
centered left, and so on.

 By default, all child views are drawn at the top-left of the


layout, so you must define the position of each view using
the various layout properties available
from RelativeLayout.LayoutParams and few of the
important attributes are given below −
Example
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.
Example

You might also like