ANDROID APPLICATION
APPROACH
Android follows code-behind approach
(a) Application Layout (UI Design)
-->
.xml
-->
.java code
Ex. (test.xml)
(b) Logic File
Ex. (JTest.java)
Android Application
= Markup + Code
System Packages
import android.widgets.*;
Super Class
Activity or ActionBarActivity
1
System Packages
Super Class
Activity or ActionBarActivity
Byte Code
Conversion
Output
Output
JAVA VM (JVM)
1.
It is a register machine
It is a stack machine
2.
3.
Maintained by Oracle
2. UI Containers
3. UI Controls
4.Event
1. Activity
Basic building blocks for developing both native & web applications
Every GUI application starts with an Activity.
We can programmatically and manually create a activity, we can
inherit a activity from the Activity super class
Package:
android.app.*;
2. Containers (Layouts)
A container for holding all controls
A container can contain another containers
Required package:
android.widgets.*;
Event Source
Event
Event Listener
Fire
event
Event Handler
Fig: Event Handling in Java
(i) Events
Objects that describe what happened
Ex. Click, TextChanged, ValueChanged, etc
(ii) Event sources
It is a component of server class
The generator of an event
Ex. Button, TextView, ImageButton, etc,
(iii) Event Listener
It is a component of client class
Used to receive & handle the event
Used to give the solution to event via Event Handler
(iv) Event Handler
It is a component of client class
A special method which gives the solution, when an event happens
Ex. Button Click Event
public void test(View v)
{
// user code
}
XML Event Handler (automated event handler)
(OR)
public void onClick(View v)
{
// user code
}
Java Event Handler (manual event handler)
7
7. TYPES OF EVENT
There are many types of events that are generated by android
Application.
These events are used to make the application more effective and
efficient.
IMPORTANT EVENT LISTENERS & EVENT HANDLERS
S.N EVENT HANDLER
EVENT LISTENER & DESCRIPTION
1. onClick()
This is called when the user either clicks or
touches or focuses upon any widget like
button, text, image etc.
2. onLongClick()
This is called when the user either clicks or
touches or focuses upon any widget like
button, text, image etc. for one or more
seconds.
3. onFocusChange()
This is called when the widget loses its
focus i.e. user goes away from the view
item.
4. onKey()
This is called when the user is focused on
the item and presses or releases a hardware
key on the device.
5. onTouch()
This is called when the user presses the
key, releases the key, or any movement
gesture on the screen.
6. onMenuItemClick()
This is called when the user selects a menu
item.
7. onCreateContextMenu() This is called when the context menu is
being built(as the result of a sustained "long
click)
IMPORTANT METHODS
(i) setText(CharSequence ch)
sets the text to UI elements like Button, TextView, etc
It takes only one argument
Return type: void
(ii) getText()
gets the text of UI elements like Button, TextView, etc
It does not take any arguments
Return type: CharSequence
I. UI WIDGETS
ANDROID UI WIDGETS
1. View
Create a view class
It is a base class for all UI widgets like Button, TextView, etc
Required package: android.widgets.*;
Screenshot
2. Button
It represents the push button
A push button that can be pressed or clicked by the user to perform
an action
Buttons allow user tom perform some action
It is very similar to JButton in swing
Types of Buttons:
Button (Button)
Image Button (ImageButton)
Toggle Button (ToggleButton)
Radio Button (RadioButton)
Important Methods
(i) setText(CharSequence ch)
Sets the string value (text) of the button
10
It takes 1 argument
Return type : void
(ii) getText()
Gets the text of the button
It does not take any arguments
Return type : CharSequence
Screenshot
3. TextView
It is used to set or get the messages (static message / dynamic
message)
It is very similar to JLabel in swing
Important Methods
(i) setText(CharSequence ch)
Sets the string value (text) of the textview
It takes 1 argument
Return type : void
11
(ii) getText()
Gets the text of the textview
It does not take any arguments
Return type : CharSequence
Screenshot
4. ImageButton
It is a special type of button
It is used for displaying images in android
Android supports 3 common image formats like PNG, JPG, GIF
along with 9 batch PNG Images
Images are stored in the directory "res/layout/drawable"
It is important to note that, all image filenames should be lowercase
and only contain letters, numbers & underscores
12
Background
Color
Image of Image
Button
13
5. ImageView
Like ImageButton, It is the base element used for displaying
images in android
It is an alternative to ImageButton
Important Methods of ImageView
(i) setImageResource(int resId)
Sets the image to ImageButton
It takes 1 argument
Return type : void
14
6. EditText
It is the pre-defined subclass of TextView that includes rich editing
capabilities
15
Screenshot
7. CheckBox
It is used to select more than one option at a time
It present options to a user, usually in a multiple choice format.
CheckBox can be selected or deselected
Any number of check boxes in the group (none or some or all) can be
selected
It is similar to JCheckBox in swing
Important Methods
(i) setText(CharSequence ch)
Sets the string value (text) of the checkbox
It takes 1 argument
Return type : void
(ii) getText()
Gets the text of the checkbox
It does not take any arguments
16
17
8. RadioButton
It is used to select only one option at a time
It present options to a user, usually in a multiple choice format.
It is similar to JRadioButton in java swing
Important Methods
(i) setText(CharSequence ch)
Sets the string value (text) of the radio button
It takes 1 argument
Return type : void
(ii) getText()
Gets the text of the radio button
It does not take any arguments
Return type : CharSequence
(iii) setChecked(boolean checked)
Used to mark radio button as checked or unchecked
Return type: void
(iv) isChecked()
It is used to find, whether checkbox is selected or not
It doesn't take any arguments
Return type: boolean
18
Screenshot
9. ToggleButton
It is a special type of button
It is used to display checked / unchecked (on/off) state on the
button (It is basically an on/off button with a light indicator)
Toggle button is very useful if you want to switch between two states.
A toggle button takes only two states ACTIVATED state &
DEACTIVATED state [or] ON state and OFF state.
The default value for on state is "ON" and for off state is "OFF".
This is the best alternative for radio buttons.
Important Methods
(i) setText(CharSequence ch)
Sets the string value (text) of the toggle button
It takes 1 argument
19
Event Listener
: setOnCheckedChangeListener()
Event Handler
10. RatingBar
It is used to get the rating from the user. (used to show rating in stars)
The rating bar shows number of stars in which the user can touch,
drag to set the value
The rating returns a floating-point number (e.g. 2.0, 3.0, 4.0, etc, ...)
It is an extension of SeekBar & ProgressBar
Android gives direct way to create the rating bars using <RatingBar> in
the xml
Important Methods
(i) setRating(int float)
Sets the rating (the number of stars filled)
It takes 1 argument
Used to set the default value of the rating.
Ex. If we set the rating at 2.0f which means 2 stars will be
selected by default
Return type : void
(ii) getRating()
gets the current rating (used to get the value of the rating bar)
It does not take any arguments
Return Type: float
21
ScreenShot
Event Listener
: OnRatingBarChangeListener
Event Handler
11. SeekBar
It is an extension of ProgressBar element
It is a kind of ProgressBar with draggable thumb.
It allows the selection of integer values using a natural user interface
It has a thumb that can be slided in order to choose a value between 0
& some maximum that can be set from the developer
The maximum value can be set either in the XML or programmatically.
Usage of SeekBar
It is used to adjust media player volume, set brightness of the screen,
seek a playing music etc.
22
Important Methods
(i) setProgress(int value)
sets the progress value (int value) of seekbar (sets the initial
value of seekbar)
It takes 1 argument
Return type : void
(ii) getProgress()
gets the current progress of seek bar (gets the current value of
seekbar)
Return type: int
Screenshot
Event Listener
: OnSeekBarChangeListener
Event Handler
12. Spinner
It is like the dropdown menu with multiple values from which the user
can select only one
It is used to select only one value (either none or one item) from the list
of options (set)
It is similar to JComboBox in swing
Important Methods of Spinner
(i) getSelectedItme()
Gets the selected item from JComboBox
Return Type : Object
(ii) getItemAtPosition(int pos)
Gets the index position of the currently selected item in the
spinner
Return Type : Object
(iii) setAdapter(SpinnerAdapter sp)
Sets the adapter object to spinner
Return type: void
Event Listener
: OnItemSelectedListener\
Event Handler
:
public void onItemSelected(AdapterView<?> parent, View v, int
position,
long id) {
// user code
sp.setText(items[position]);
}
Spinner Object
public void onNothingSelected(AdapterView<?> parent) {
sp.setText("");
24
}
Screenshot
13. TimePicker
It is used to select time. It allows user to select time by hour and
minute.
We cannot select time by seconds.
25
Screenshot
14. WebView
It is an extension of the view class that helps displays web content
If we want to deliver a web application (web apps) as a part of client
application, we can do it using webview Layout
It is used to display the web page inside the activity
It does not include any features of a fully developed web browser, such
as navigation controls or an address bar.
It doesn't support all features of a regular browser but we can enable
Javascript inside our Web View and also override the Back button to
view if there are any history pages.
26
IMPORTANT METHODS
1. loadUrl(String url)
It is used to load a web page using an URL
It takes only one argument
Return Type: void
Ex.
wb.loadUrl("www.google.com");
2. loadData(String htmlData, String mime, String Encoding)
It is used to load data from an HTML string
It takes 3 arguments
Return Type: void
Ex.
String html= "<html><body>A very basic <b>WebView</b>
demo!</body></html>";
wb.loadData(html, "text/html", null);
Screenshot
27
II. UI LAYOUTS
LAYOUTS or CONTAINERS
Layout denotes the architecture of the application, where and how
the controls should be organized in the UI
It is classes that can have other components on it
So for creating a GUI, we need at least one container object
To design UI for an App, we need to know about Android Layout. It is
also known as ViewGroup.
1. Activity
Main screen in GUI
It is a top level layout with its own title, icon, settings menu (Action Bar)
It holds other UI Layouts & UI Widgets
2. LinearLayout
It is the simplest layout
It is a view group that arranges all children in a single direction
vertically or horizontally (All the UI elements are displayed in a linear /
sequential fashion, either horizontally or vertically with help of
"android:orientation" attribute)
28
Screenshot
3. RelativeLayout
It is the flexible layout for all
It is a view group, that displays child views in relative positions (All
the UI elements are arranged in relative to each other)
For ex, we can set a UI element to be positioned "above" or "below" or
"to the left of" or "to the right of" another control, referred to by its
unique identifier
29
Screenshot
4. FrameLayout
It is designed to display a stack of child view controls (UI widgets)
It allows the UI elements to be overlapped with each other
Multiple view controls (UI elements) can be added to this layout (This
can be used to show multiple controls within the same screen space)
Screenshot
30
5. TableLayout
A table layout is a grid which contains rows & columns
It arranges its children in tabular view-Rows & Columns (All the
controls are arranged into rows & columns)
It is same as HTML table
<TableLayout> is the parent and <TableRow> is its child. This is
similar to HTML <table> and <tr>
<TableRow> can contain any UI elements like Button, TextView,
EditText, etc
Screenshot
31
6. ScrollView
It is a special type of FrameLayout that allows users to scroll through a
list of views that occupy more space than the physical display
Conditions
The ScrollView can contain only one child view or ViewGroup, which
normally is a LinearLayout.
Screenshot
32
7. AbsoluteLayout
It is used for placing UI elements at the exact location on the screen
using x and y co-ordinates
As shown below in the XML, for both EditText & Button 'x' & 'y'
coordinates have been specified via "android:layout_x" and
"android:layout_y"
Ex
<AbsoluteLayout android:id="@+id/abs"
android:layout_width="fill_parent" android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android">
<EditText android:id="@+id/EditText01" android:layout_width="200px"
android:layout_height="wrap_content" android:layout_x="12px"
android:layout_y="12px" />
<Button android:text="Search" android:id="@+id/Button01"
android:layout_width="100px" android:layout_height="wrap_content"
android:layout_x="220px" android:layout_y="12px" />
</AbsoluteLayout>
33
Screenshot
8. GridLayout
It is a ViewGroup that displays items in a two-dimensional, scrollable
grid
It is an android layout that places its children in a rectangular grid
Screenshot
34
MEANING
android:id
Resource ID
Syntax:
android:id=@+id/name
Ex.
android:id=@+id/tb
@ global variable
+ The plus symbol
indicates This is a new
resource name that must be
created & added to our
R.class file
2.
android:layout_height
Ex.
android:layout_height=
fill_parent
(OR)
android:layout_height=
match_parent
(OR)
android:layout_height=
wrap_content
(OR)
android:layout_height=
100dp sets the custom
height using dp value
3.
android:layout_width
Ex.
android:layout_width
=fill_parent
android:layout_width
=match_parent
android:layout_width
=wrap_content
android:layout_width
=55dp
4.
android:text
Ex.
android:text=Hello World
(OR)
android:text=@string/lb
<string name=lb>Hello
World</string>
5.
android:textStyle
Ex.
android:textSyle=bold
android:textSyle=normal
android:textSyle=italic
6.
android:textSize
Ex.
android:textSyle=18sp
7.
android:textColor
Ex.
8.
android:background
Ex.
android: background=12ffff
37
9.
android:src
Syntax:
android:src=@drawable/
imageName
Ex.
android:src=@drawable/mit
mit.png
10
android:onClick
Ex.
android:onClick=test
// Event Handler
public void test(View v)
{
// code
}
NOTE
Difference b/w android:id=@+id/name & android:id=@id/name
android:id=@+id/tb means we are adding a new UI widget (view)
with the name tb in our R.class file
android:id=@id/tb means we are using or referring an already
defined UI widget (view) with the name tb in our R.class file
38
TERMINOLOGIES IN ANDROID
Screen Size
Screen size in android is grouped into categories small, medium, large,
extra-large, double-extra & triple-extra
Screen Density
Screen density is the amount of pixels within an area (like inch) of the
screen.
Generally it is measured in dots-per-inch (dpi).
Screen density is grouped as low, medium, high and extra high.
Resolution
Resolution is the total number of pixels in the screen
dp
Density Independent Pixel, it varies based on screen density
In 160 dpi screen, 1dp=1pixel
Except for font size, use dp always
dip
dip=dp. In earlier android versions dip was used & later changed
to dp
sp
Scale Independent Pixel, scale based on users font size
preference.
Fonts should use sp
px
Pixels-corresponds to actual pixels on the screen
39
in
Inches-based on the physical size of the screen
1 inch=2.54 centimeters
mm
Millimeters-based on the physical size of the screen
pt
Points-1/72 of an inch, based on the physical size of the screen
NOTE
Always use dp & sp only. sp for font size & dp for everything else (e.g.
Height, Width, etc, )
It will make UI compatible for android devices with different
densities
40
: Code-Behind
UI Design
: XML
Logic
: Java
1. XML CODE
(test.xml)
<LinearLayout 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:background="#000"
tools:context=".JTest" >
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/tb"
android:textColor="#2ad2c9"
android:textSize="22sp"
android:textStyle="bold"
/>
</LinearLayout>
41
2. JAVA CODE
package com.example.textviewdemo;
import android.os.Bundle;
import android.app.Activity;
import android.widget.*;
// sub class should inherit the super class Activity
public class JTest extends Activity {
TextView tv;
// called when activity is 1st created
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set the specific layout file for current screen
setContentView(R.layout.test);
// find XML resource
tv=(TextView)findViewById(R.id.tb);
// display message
tv.setText("Welcome to Android Programming...");
}
}
42
43
44
5. AVD CREATION
45
6. OUTPUT
46
: Code-Behind
UI Design
: XML
Logic
: Java
47
48
49
50
51
1. XML CODE
(test.xml)
res/layout/test.xml
<LinearLayout
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:background="#ffffff">
<TextView
android:text="Hello World!"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="60dp"
android:textColor="#1277e1"
android:textStyle="bold"
android:gravity="center"
android:textSize="18sp"
/>
</LinearLayout>
2. JAVA CODE
(JTest.java)
package ganesh.pugazh.helloworld;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
// current class must extend the super class AppCompactActivity
public class JTest extends AppCompatActivity {
// called when activity is 1st created
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
52
53
54
55
56
57
58
59
6. OUTPUT
NOTE:
For classic native application, the current class must extend
Activity super class
For material design native application, the current class must
extend AppCompactActivity super class.
60
: Inline-Coding
UI Design
: Java
Logic
1. JAVA CODE
: Java
(JTest.java)
package com.example.textviewdemo;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.widget.*;
public class JTest extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create TextView Object
TextView tv=new TextView(this);
// set the Text Size
tv.setTextSize(20.0f);
// display message
tv.setText("Good Morning :-)");
// set the TextView to Current Screen via setContentView
setContentView(tv);
61
}
}
2. OUTPUT
62
: Inline-Coding
UI Design
: Java
Logic
1. JAVA CODE
: Java
(JTest.java)
package com.example.textviewdemo;
import android.os.Bundle;
import android.app.Activity;
import android.graphics.Color;
import android.view.*;
import android.widget.*;
public class JTest extends Activity {
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Create TextView Object
TextView tv=new TextView(this);
//
Set the background color
tv.setBackgroundColor(Color.parseColor("#331e54"));
// set the foreground color
tv.setTextColor(Color.parseColor("#f7f7f7"));
// set the Text Size
tv.setTextSize(20.0f);
// display message
tv.setText("Good Morning :-)");
// set the TextView to Current Screen via setContentView
63
setContentView(tv);
}
}
USED METHODS
1. setText(CharSequence msg)
2. OUTPUT
64
: Click
Event Handler
: test() onClick()
65
Ex.
Button bt;
public void onCreate(Bundle b)
{
bt=(Button)findViewById(R.id.button);
// register & assign events
bt.setOnClickListener(this);
}
Event Generator
// Event Handler
public void onClick(View v)
{
// user code
}
Event Listener
Event Location
Event Handler
66
1. INITIAL DESIGN
android:text="@string/l1"
android:background="#0099e5"
android:textColor="#f7f7f7"
android:textSize="18sp"
android:textStyle="bold"
android:onClick="test"
/>
(Automatic event handler)
<TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dp"
android:textSize="18sp"
android:textColor="#f7f7f7"
/>
</LinearLayout>
(string.xml)
<resources>
<string name="app_name">ButtonDemo</string>
<string name="action_settings">Settings</string>
<string name="hello_world">Hello world!</string>
<string name="l1">Click Me</string>
</resources>
3. ACTIVITY JAVA CODE
package krish.pugazh.button1demo;
import android.os.Bundle;
// supports Bundle class
import android.app.Activity;
// supports Activity class (super class)
import android.view.*;
// supports View & Menu classes
import android.widget.*;
// supports UI elements like Button,
public class JButtonExample extends Activity {
// TextView Element Declaration
TextView tb;
68
2. append(CharSequence msg)
Add the text messages at the end of the TextView
This method takes only one argument
Return type: void
69
4. OUTPUT
70
3. OUTPUT
73
: Click
Event Handler
: info() onClick()
/>
</LinearLayout>
(string.xml)
<resources>
<string name="app_name">ImageButton</string>
<string name="cc"></string>
</resources>
2. ACTIVITY CODE (.java)
(JTest.java)
import android.os.Bundle;
import android.app.Activity;
import android.view.*;
import android.widget.*;
public class JTest extends Activity {
TextView tw;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set the specific layout to current activity
setContentView(R.layout.test);
// find XML resources & map them to java widget
tw=(TextView)findViewById(R.id.tb);
}
// Image Button Code
public void info(View v)
{
tw.setText("This is Hike Image...");
}
}
75
3. OUTPUT
3.1 SCREENSHOT1
76
3.2 SCREENSHOT2
DERIVATION
Object
Dialog class
Alert Dialog
6. setIcon(Drawable icon)
It is used set the icon of the alert dialog box
It takes only one argument
Return type: AlertDialog.Builder
7. show()
It is used to show the alert dialog box
It does not take any arguments
Return type: AlertDialog.Builder
android:onClick="disp"
android:textSize="20sp"
android:background="#463014"
android:textColor="#f7f7f7"
android:text="@string/lb"
/>
</RelativeLayout>
(string.xml) [/res/values/string.xml]
<resources>
<string name="app_name">AlertDemo</string>
<string name="lb">Click</string>
</resources>
2. ACTIVITY CODE (.java)
(JAlert.java) [/src/ram.pugazh.alertdemo/JAlert.java]
package ram.pugazh.alertdemo;
import android.os.Bundle;
import android.view.*;
import android.app.*;
import android.content.DialogInterface;
// Sub class must extends the super class Activity
public class JAlert extends Activity {
// this method is called when an app is loaded
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// set the specific layout to current screen
setContentView(R.layout.alert);
}
82
The button that was clicked (e.g. bt) or the position of the
item clicked
@Override
public void onClick(DialogInterface dg, int id) {
dg.cancel();
}
});
ab.show();
}
}
3. OUTPUT
3.1 SCREENSHOTS
84
3.2 SCREENSHOTS
85
android:shape=line
2. Stroke
It is the sub element of shape element
It is used to set the border width & border color of button
Important attributes
android:width=2dp
android:color=#000
3. Corners
It is the sub element of shape element
86
android:topRightRadius=2dp
corner
87
: Click
Event Handler
: info() onClick()
88
(circledesign.xml) [/res/drawable/circledesign.xml]
<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="oval"
>
<stroke
android:width="2.5dp"
android:color="#fbb034"
/>
<solid
android:color="#0091cd"
/>
</shape>
(string.xml) [/res/values/string.xml]
<resources>
<string name="app_name">Cutebutton</string>
<string name="m1">Click</string>
</resources>
2. ACTIVITY CODE (.java)
(JCircle.java) [/src/ram.pugazh.cutebutton/JCircle.java]
import android.os.Bundle;
import android.app.*;
import android.view.*;
public class JCircle extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.circle);
}
89
90
3.2 SCREENSHOTS
Title
Message
Postive Button
91