You are on page 1of 76

Mobile Application Development

By
FAHAD ASLAM
Chapter 2
 Create a New Project
 Anatomy of Android Application
 Layout
◦ Write the XML
◦ Attributes
◦ Load the XML Resource
◦ ID
◦ Layout Parameters
◦ Layout Position
◦ Size, Padding and Margins
◦ Common Layouts
Create Android Application
Anatomy of Android Application
Sr.No. Folder, File & Description

1 Java
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.

2 res/drawable-hdpi
This is a directory for drawable objects that are designed for
high-density screens.

3 res/layout
This is a directory for files that define your app's user
interface.
Sr.No. Folder, File & Description

4 res/values
This is a directory for other various XML files that contain a
collection of resources, such as strings and colours definitions.

5 AndroidManifest.xml
This is the manifest file which describes the fundamental
characteristics of the app and defines each of its components.

6 Build.gradle
This is an auto generated file which contains
compileSdkVersion, buildToolsVersion, applicationId,
minSdkVersion, targetSdkVersion, versionCode and versionName
Intent
 Android uses Intent for communicating between the
components of an Application and also from one
application to another application.
 Intent are the objects which is used in android for
passing the information among Activities in an
Application and from one app to another also. Intent are
used for communicating between the Application
components and it also provides the connectivity
between two apps.
 For example: Intent facilitate you to redirect your
activity to another activity on occurrence of any event.
By calling, startActivity() you can perform this task.
Types of intent
 Implicit
 In Implicit Intents we do need to specify the name of the
component. We just specify the Action which has to be performed
and further this action is handled by the component of another
application.
 The basic example of implicit Intent is to open any web page
 Explicit
 Explicit Intents are used to connect the application internally.
 In Explicit we use the name of component which will be affected
by Intent. For Example: If we know class name then we can
navigate the app from One Activity to another activity using Intent.
In the similar way we can start a service to download a file in
background process.
Android Activity life Cycle
Activity
 An Android activity is one screen of the Android app's
user interface. In that way an Android activity is very
similar to windows in a desktop application. An Android
app may contain one or more activities, meaning one or
more screens. The Android app starts by showing the
main activity, and from there the app may make it
possible to open additional activities
Android Activity life Cycle
 If you have worked with C, C++ or Java programming
language then you must have seen that your program
starts from main() function.
 Android system initiates its program with in
an Activity starting with a call on onCreate() callback
method.
 Android Activity Lifecycle is controlled by 7 methods
of android.app.Activity class.
Fragment
 A Fragment is a piece of an activity which enable more modular
activity design. It will not be wrong if we say, a fragment is a kind
of sub-activity.
 Following are important points about fragment −
 A fragment has its own layout and its own behavior 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.
 Fragment life cycle is closely related to the life cycle of its host activity
which means when the activity is paused, all the fragments available in
the activity will also be stopped.
Fragment Life Cycle
 onAttach()The fragment instance is associated with an activity
instance.The fragment and the activity is not fully initialized.
Typically you get in this method a reference to the activity which
uses the fragment for further initialization work.
 onCreate() The system calls this method when creating the
fragment. You should initialize essential components of the
fragment that you want to retain when the fragment is paused or
stopped, then resumed.
 onCreateView() The system calls this callback when it's time for
the fragment to draw its user interface for the first time. To draw a
UI for your fragment, you must return a View component from this
method that is the root of your fragment's layout. You can return
null if the fragment does not provide a UI.
 onActivityCreated()The onActivityCreated() is called after the
onCreateView() method when the host activity is created. Activity
and fragment instance have been created as well as the view
hierarchy of the activity. At this point, view can be accessed with
the findViewById() method. example. In this method you can
instantiate objects which require a Context object
 onStart()The onStart() method is called once the fragment gets
visible.
 onResume()Fragment becomes active.
 onPause() The system calls this method as the first indication that
the user is leaving the fragment. This is usually where you should
commit any changes that should be persisted beyond the current
user session.
 onStop()Fragment going to be stopped by calling onStop()
 onDestroyView()Fragment view will destroy after call this method
 onDestroy()onDestroy() called to do final clean up of the
fragment's state but Not guaranteed to be called by the Android
platform.
Basic XML Layouts - Containers
Designing Complex Uis
 Arguably, LinearLayout is the most common modeling
tool. It offers a "box" model similar to the Java-Swing
Box-Layout. • Generally, complex UI designs result
from the combination of simpler nested boxes that show
their inner pieces using a horizontal or vertical
orientation
Basic XML Layouts - Containers
Summary of Commonly-used Android
containers
1. LinearLayout (the box model),
2. RelativeLayout (a rule-based model), and
3. TableLayout (the grid model), along with
4. ScrollView, a container designed to assist
with implementing scrolling containers.
5. Other (ListView, GridView, WebView,
MapView,…) discussed later
Basic XML Layouts - Containers
1. Linear Layout
LinearLayout is a box model – widgets or child
containers are lined up in a column or row, one after
the next. To configure a LinearLayout, you have five
main areas of control besides the container's contents:
• orientation,
• fill model,
• weight,
• gravity,
• padding ,
• margin
Basic XML Layouts - Containers
1. Linear Layout
 Orientation

indicates whether the LinearLayout represents a row or a


column.

Add the android:orientation property to your


LinearLayout element in your XML layout, setting the
value to be horizontal for a row or vertical for a
column.
The orientation can be modified at runtime by invoking
setOrientation()
Basic XML Layouts - Containers
1.1 Linear Layout: Orientation
 indicates whether the LinearLayout
represents a row (HORIZONTAL) or a
column (VERTICAL).
Layout
 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
ViewGroup is an invisible container that defines the layout
structure for View and other ViewGroup objects
 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 .
 You can declare a layout in two ways:
 Declare UI elements in XML. Android provides a straightforward
XML vocabulary that corresponds to the View classes and
subclasses, such as those for widgets and layouts. You can also use
Android Studio's Layout Editor to build your XML layout using a
drag-and-drop interface.
 Instantiate layout elements at runtime. Your app can create View
and ViewGroup objects (and manipulate their properties)
programmatically.
Write the XML
 Using Android's XML vocabulary, you can quickly design UI
layouts and the screen elements they contain, in the same way
you create web pages in HTML — with a series of nested
elements.
 Each layout file must contain exactly one root element, which
must be a View or ViewGroup object. Once you've defined
the root element, you can add additional layout objects or
widgets as child elements to gradually build a View hierarchy
that defines your layout. For example, here's an XML layout
that uses a vertical LinearLayout to hold a TextView and a
Button:
 After you've declared your layout in XML, save the file with
the .xml extension, in your Android
project's res/layout/ directory, so it will properly compile.
 More information about the syntax for a layout XML file is
available in the Layout Resources document.
Load the XML Resource
 When you compile your app, each XML layout file is
compiled into a View resource. You should load the
layout resource from your app code, in your
Activity.onCreate() callback implementation. Do so by
calling setContentView(), passing it the reference to
your layout resource in the form
of: R.layout.layout_file_name. For example, if your
XML layout is saved as main_layout.xml, you would
load it for your Activity like so:
The onCreate() callback method in your
Activity is called by the Android
framework when your Activity is
launched (see the discussion about
lifecycles, in the Activities document).
Attributes
 Every View and ViewGroup object supports their own
variety of XML attributes. Some attributes are specific
to a View object (for example, TextView supports
the textSize attribute), but these attributes are also
inherited by any View objects that may extend this class.
Some are common to all View objects, because they are
inherited from the root View class (like the id attribute).
And, other attributes are considered "layout parameters,"
which are attributes that describe certain layout
orientations of the View object, as defined by that
object's parent ViewGroup object.
ID
 Any View object may have an integer ID associated with it, to
uniquely identify the View within the tree. When the app is
compiled, this ID is referenced as an integer, but the ID is typically
assigned in the layout XML file as a string, in the id attribute. This
is an XML attribute common to all View objects (defined by the
View class) and you will use it very often. The syntax for an ID,
inside an XML tag is:
 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 (in the R.java file). There are a number of other ID
resources that are offered by the Android framework. When
referencing an Android resource ID, you do not need the plus-
symbol, but must add the android package namespace, like so:
 With the android package namespace in place, we're
now referencing an ID from the android.R resources
class, rather than the local resources class.
 In order to create views and reference them from the
app, a common pattern is to:
1. Define a view/widget in the layout file and assign it a
unique ID:
2. Then create an instance of the view object and capture it from the
layout (typically in the onCreate() method)

 Defining IDs for view objects is important when creating a


RelativeLayout. In a relative layout, sibling views can define their
layout relative to another sibling view, which is referenced by the
unique ID.
 An ID need not be unique throughout the entire tree, but it should be
unique within the part of the tree you are searching (which may often
be the entire tree, so it's best to be completely unique when possible)
Layout Parameters
 XML layout attributes named layout_something define
layout parameters for the View that are appropriate for
the ViewGroup in which it resides.
 Every ViewGroup class implements a nested class that
extends ViewGroup.LayoutParams. This subclass
contains property types that define the size and position
for each child view, as appropriate for the view group.
As you can see in figure 2, the parent view group
defines layout parameters for each child view (including
the child view group).
 Note that every LayoutParams subclass has its own syntax for
setting values. Each child element must define LayoutParams that
are appropriate for its parent, though it may also define different
LayoutParams for its own children.
 All view groups include a width and height
(layout_width and layout_height), and each view is required to
define them. Many LayoutParams also include optional margins
and borders.
 You can specify width and height with exact measurements, though
you probably won't want to do this often. More often, you will use
one of these constants to set the width or height:
 wrap_content tells your view to size itself to the dimensions
required by its content.
 match_parent tells your view to become as big as its parent view
group will allow.
Layout Position
 The geometry of a view is that of a rectangle. A view has a location,
expressed as a pair of left and top coordinates, and two dimensions,
expressed as a width and a height. The unit for location and dimensions
is the pixel.
 It is possible to retrieve the location of a view by invoking the methods
getLeft() and getTop(). The former returns the left, or X, coordinate of
the rectangle representing the view. The latter returns the top, or Y,
coordinate of the rectangle representing the view. These methods both
return the location of the view relative to its parent. For instance,
when getLeft() returns 20, that means the view is located 20 pixels to
the right of the left edge of its direct parent.
 In addition, several convenience methods are offered to avoid
unnecessary computations, namely getRight() and getBottom(). These
methods return the coordinates of the right and bottom edges of the
rectangle representing the view. For instance, calling getRight() is
similar to the following computation: getLeft() + getWidth().
Size, Padding and Margins
 The size of a view is expressed with a width and a height. A view
actually possesses two pairs of width and height values.
 The first pair is known as measured width and measured height.
These dimensions define how big a view wants to be within its
parent. The measured dimensions can be obtained by calling
getMeasuredWidth() and getMeasuredHeight().
 The second pair is simply known as width and height, or
sometimes drawing width and drawing height. These dimensions
define the actual size of the view on screen, at drawing time and
after layout. These values may, but do not have to, be different from
the measured width and height. The width and height can be
obtained by calling getWidth() and getHeight().
 To measure its dimensions, a view takes into account its padding.
The padding is expressed in pixels for the left, top, right and bottom
parts of the view. Padding can be used to offset the content of the
view by a specific number of pixels. For instance, a left padding of
2 will push the view's content by 2 pixels to the right of the left
edge. Padding can be set using the setPadding(int, int, int, int)
method and queried by calling getPaddingLeft(), getPaddingTop(),
getPaddingRight() and getPaddingBottom().
Common Layouts
 Each subclass of the ViewGroup class provides a unique way to
display the views you nest within it. Below are some of the more
common layout types that are built into the Android platform.
◦ Linear Layout
◦ Relative Layout
◦ Web View
 Linear Layout
A layout that organizes its children into a single
horizontal or vertical row. It creates a scrollbar if the
length of the window exceeds the length of the screen.
 Relative layout
Enables you to specify the location of child objects
relative to each other (child A to the left of child B) or
to the parent (aligned to the top of the parent).
 Web View
Displays web pages.
The Main Activity File
MainActivity.java.
 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.
App Manifest Overview
 Every app project must have an AndroidManifest.xml file (with
precisely that name) at the root of the project source set. The
manifest file describes essential information about your app to the
Android build tools, the Android operating system, and Google Play.
 The app's package name, which usually matches your code's
namespace. The Android build tools use this to determine the
location of code entities when building your project. When
packaging the app, the build tools replace this value with the
application ID from the Gradle build files, which is used as the
unique app identifier on the system and on Google Play.
The manifest file's root element requires an attribute for your app's
package name (usually matching your project directory structure—
the Java namespace).
 For example, the following snippet shows the root <manifest>
element with the package name "com.example.myapp":
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
 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
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
 This is an example of simple RelativeLayout which we will study in
a separate chapter. 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!"
Running the Application

You might also like