0% found this document useful (0 votes)
56 views37 pages

WCMC Lesson3

This document discusses Android user interface development. It describes how all UI elements in Android are built using View and ViewGroup objects. Common layouts like LinearLayout and RelativeLayout are described, as well as layout attributes. The document also covers creating UI controls like TextView and Button in XML layout files. Finally, it discusses Android events like click listeners, and how to register event listeners by implementing interfaces or using anonymous inner classes.

Uploaded by

betselot tadesse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
56 views37 pages

WCMC Lesson3

This document discusses Android user interface development. It describes how all UI elements in Android are built using View and ViewGroup objects. Common layouts like LinearLayout and RelativeLayout are described, as well as layout attributes. The document also covers creating UI controls like TextView and Button in XML layout files. Finally, it discusses Android events like click listeners, and how to register event listeners by implementing interfaces or using anonymous inner classes.

Uploaded by

betselot tadesse
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 37

Chapter Three

Android Application Development


3.1 Android User Interface
• All user interface elements in an Android app are built
using View and ViewGroup objects.
• A View is an object that draws something on the screen that the
user can interact with.
• View is the base class for widgets, which are used to create
interactive UI components like buttons, text fields, etc.
• A ViewGroup is an object that holds other View (and ViewGroup)
objects in order to define the layout of the interface.
• The ViewGroup is a subclass of View and provides invisible
container that hold other Views or other ViewGroups and define
their layout properties.
• Android provides a collection of
both View and ViewGroup subclasses that offer you common input
controls (such as buttons and text fields) and various layout models
(such as a linear or relative layout).
…continued
• A layout may contain any type of widgets such as buttons,
labels, textboxes, and so on. For Example:
<?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"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a TextView" />
<Button android:id="@+id/button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="This is a Button" />

<!-- More GUI components go here -->

</LinearLayout>
• Once your layout is defined, you can load the
layout resource from your application code, in
yourActivity.onCreate() callback implementation
as shown below:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
Android Layout Types
• LinearLayout is a view group that aligns all children in a
single direction, vertically or horizontally.
• RelativeLayout is a view group that displays child views
in relative positions.
• TableLayout is a view that groups views into rows and
columns.
• AbsoluteLayout enables you to specify the exact
location of its children.
• FrameLayout is a placeholder on screen that you can
use to display a single view.
• ListView is a view group that displays a list of scrollable
items.
• 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(ID, Layout Position, Size, Padding
and Margin)
• android:id :- This is the ID which uniquely identifies the view.
• android:layout_marginTop:-This is the extra space on the top
side of the layout.
• android:layout_marginBottom:- This is the extra space on the
bottom side of the layout.
• android:layout_marginLeft:- This is the extra space on the left
side of the layout.
• android:layout_marginRight:-This is the extra space on the
right side of the layout.
• android:layout_gravity:-This specifies how child Views are
positioned.
• android:layout_weight:- This specifies how much of the extra
space in the layout should be allocated to the View.
…continued
• android:layout_x:- This specifies the x-coordinate of the
layout.
• android:layout_y:- This specifies the y-coordinate of the
layout.
• android:layout_width:- This is the width of the layout.
• android:layout_width:- This is the width of the layout.
• android:paddingLeft:- This is the left padding filled for
the layout.
• android:paddingRight:- This is the right padding filled for
the layout.
• android:paddingTop:- This is the top padding filled for the
layout.
• android:paddingBottom:- This is the bottom padding filled
for the layout.
Android UI Controls
• TextView:- This control is used to display text to the user.
• EditText:- EditText is a predefined subclass of TextView that includes rich editing
capabilities.
• 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.
• Button:- A push-button that can be pressed, or clicked, by the user to perform an
action.
• CheckBox:- An on/off switch that can be toggled by the user. You should use
checkboxes when presenting users with a group of selectable options that are not
mutually exclusive.
• ToggleButton:- An on/off button with a light indicator.
• RadioButton:- The RadioButton has two states: either checked or unchecked.
• RadioGroup:- A RadioGroup is used to group together one or more RadioButtons.
• ProgressBar:- The ProgressBar view provides visual feedback about some ongoing
tasks, such as when you are performing a task in the background.
• Spinner:- A drop-down list that allows users to select one value from a set.
• TimePicker:- The TimePicker view enables users to select a time of the day, in either
24-hour mode or AM/PM mode.
• DatePicker:-The DatePicker view enables users to select a date of the day.
Create UI Controls
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);
3.2 Android Events
• Events are a useful way to collect data about a user's interaction
with interactive components of your app, like button presses or
screen touch etc.
• The Android framework maintains an event queue into which events
are placed as they occur and then each event is removed from the
queue on a first-in, first-out (FIFO) basis.
• You can capture these events in your program and take appropriate
action as per requirements.
There are following three concepts related to Android Event
Management:
• Event Listeners: The View class is mainly involved in building up a
Android GUI, same View class provides a number of Event Listeners.
• The Event Listener is the object that receives notification when an
event happens.
• Event Listeners Registration: Event Registration is the process by
which an Event Handler gets registered with an Event Listener so
that the handler is called when the Event Listener fires the event.
• Event Handlers: When an event happens and we have registered
and event listener for the event, the event listener calls the Event
Handlers, which is the method that actually handles the event.
Event Listeners & Event Handlers
Event Handler Event Listener & Description

OnClickListener()
onClick() This is called when the user either clicks or touches or focuses upon any widget like
button, text, image etc. You will use onClick() event handler to handle such event.
OnLongClickListener()
This is called when the user either clicks or touches or focuses upon any widget like
onLongClick()
button, text, image etc. for one or more seconds. You will use onLongClick() event
handler to handle such event.
OnFocusChangeListener()
onFocusChang
This is called when the widget looses its focus ie. user goes away from the view item.
e()
You will use onFocusChange() event handler to handle such event.
OnFocusChangeListener()
onKey() This is called when the user is focused on the item and presses or releases a
hardware key on the device. You will use onKey() event handler to handle such event.
OnTouchListener()
onTouch() This is called when the user presses the key, releases the key, or any movement
gesture on the screen. You will use onTouch() event handler to handle such event.
OnMenuItemClickListener()
onMenuItemCli
This is called when the user selects a menu item. You will use onMenuItemClick()
ck()
event handler to handle such event.
Event Listeners Registration
• Event Registration is the process by which an
Event Handler gets registered with an Event
Listener so that the handler is called when the
Event Listener fires the event.
• There are several tricky ways to register your
event listener for any event. I'm going to show
you only top 3 ways:
a) Using an Anonymous Inner Class
b) Activity class implements the Listener interface.
c) Using Layout file activity_main.xml to specify
event handler directly.
Examples

• EVENT LISTENERS REGISTRATION USING AN


ANONYMOUS INNER CLASS (EXAMP)
• REGISTRATION USING THE ACTIVITY
IMPLEMENTS LISTENER INTERFACE(EXAMP1)
• Using Layout file activity_main.xml to specify
event handler directly(EXAMP2)
EXAMPLE FOR EVENT LISTENERS REGISTRATION USING AN ANONYMOUS
INNER CLASS (EXAMP)
• package com.examp;

• import android.os.Bundle;
• import android.app.Activity;
• import android.view.Menu;
• import android.view.View;
• import android.widget.Button;
• import android.widget.TextView;

• public class MainActivity extends Activity {

• @Override
• protected void onCreate(Bundle savedInstanceState) {
• super.onCreate(savedInstanceState);
• setContentView(R.layout.activity_main);
• //--- find both the buttons---
• Button sButton = (Button) findViewById(R.id.button_s);
• Button lButton = (Button) findViewById(R.id.button_l)
• // -- register click event with first button ---
• sButton.setOnClickListener(new View.OnClickListener() {
• public void onClick(View v) {
• // --- find the text view --
• TextView txtView = (TextView) findViewById(R.id.text_id);
• // -- change text size --
• txtView.setTextSize(14);
• }
• });

• // -- register click event with second button ---
• lButton.setOnClickListener(new View.OnClickListener() {
• public void onClick(View v) {
• // --- find the text view --
• TextView txtView = (TextView) findViewById(R.id.text_id);
• // -- change text size --
• txtView.setTextSize(24);
• }
• });
• }


• @Override
• public boolean onCreateOptionsMenu(Menu
menu) {
• // Inflate the menu; this adds items to the
action bar if it is present.
• getMenuInflater().inflate(R.menu.main,
menu);
• return true;
• }

• }
EXAMPLE FOR REGISTRATION USING THE ACTIVITY
IMPLEMENTS LISTENER INTERFACE
1. Xml file
• <?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" >

• <Button
• android:id="@+id/button_s"
• android:layout_height="wrap_content"
• android:layout_width="match_parent"
• android:text="@string/button_small"/>
• <Button
• android:id="@+id/button_l"
• android:layout_height="wrap_content"
• android:layout_width="match_parent"
• android:text="@string/button_large"/>

• <TextView
• android:id="@+id/text_id"
• android:layout_width="wrap_content"
• android:layout_height="wrap_content"
• android:text="@string/hello_world" />

• </LinearLayout>
2. String.xml
• <?xml version="1.0" encoding="utf-8"?>
• <resources>

• <string name="app_name">Examp1</string>
• <string name="action_settings">Settings</string>
• <string name="hello_world">Hello world!</string>
• <string name="button_small">Small Font</string>
• <string name="button_large">Large Font</string>

• </resources>
3. Ex.java(Java File)
• package com.examp1;
• import android.os.Bundle;
• import android.app.Activity;
• import android.view.Menu;
• import android.view.View;
• import android.view.View.OnClickListener;
• import android.widget.Button;
• import android.widget.TextView;

• public class Ex1 extends Activity implements OnClickListener{

• @Override
• protected void onCreate(Bundle savedInstanceState) {
• super.onCreate(savedInstanceState);
• setContentView(R.layout.activity_ex1);
• //--- find both the buttons---
• Button sButton = (Button) findViewById(R.id.button_s);
• Button lButton = (Button) findViewById(R.id.button_l);
• // -- register click event with first button ---
• sButton.setOnClickListener(this);
• // -- register click event with second button ---
• lButton.setOnClickListener(this);
• }

• //--- Implement the OnClickListener callback
• public void onClick(View v) {
• if(v.getId() == R.id.button_s)
• {
• // --- find the text view --
• TextView txtView = (TextView) findViewById(R.id.text_id);
• // -- change text size --
• txtView.setTextSize(14);
• return;
• }
• if(v.getId() == R.id.button_l)
• {
• // --- find the text view --
• TextView txtView = (TextView) findViewById(R.id.text_id);
• // -- change text size --
• txtView.setTextSize(24);
• return;
• }

• }

• @Override
• public boolean onCreateOptionsMenu(Menu menu) {
• // Inflate the menu; this adds items to the action bar if it is
present.
• getMenuInflater().inflate(R.menu.ex1, menu);
• return true;
• }
Example for Using Layout file activity_main.xml to
specify event handler directly
1. Main.xml
• <?xml version="1.0" encoding="utf-8"?>
• <LinearLayout
xmlns:android="http://schemas.android.com/apk/res/androi
d"
• android:layout_width="fill_parent"
• android:layout_height="fill_parent"
• android:orientation="vertical" >

• <Button
• android:id="@+id/button_s"
• android:layout_height="wrap_content"
• android:layout_width="match_parent"
• android:text="@string/button_small"
• android:onClick="doSmall"/>
• <Button
• android:id="@+id/button_l"
• android:layout_height="wrap_content"
• android:layout_width="match_parent"
• android:text="@string/button_large"
• android:onClick="doLarge"/>

• <TextView
• android:id="@+id/text_id"
• android:layout_width="wrap_content"
• android:layout_height="wrap_content"
• android:text="@string/hello_world" />

• </LinearLayout>
2. String.xml
• ?xml version="1.0" encoding="utf-8"?>
• <resources>

• <string name="app_name">Examp2</string>
• <string name="action_settings">Settings</string>
• <string name="hello_world">Hello
world!</string>
• <string name="button_small">Small
Font</string>
• <string name="button_large">Large Font</string>

• </resources>
3. MainActivity.Java
• package com.examp2;

• import android.os.Bundle;
• import android.app.Activity;
• import android.view.Menu;
• import android.view.View;
• import android.widget.TextView;

• public class MainActivity extends Activity {

• @Override
• protected void onCreate(Bundle savedInstanceState) {
• super.onCreate(savedInstanceState);
• setContentView(R.layout.activity_main);
• }
• //--- Implement the event handler for the first button.
• public void doSmall(View v) {
• // --- find the text view --
• TextView txtView = (TextView) findViewById(R.id.text_id);
• // -- change text size --
• txtView.setTextSize(14);
• return;
• }
• //--- Implement the event handler for the second button.
• public void doLarge(View v) {
• // --- find the text view --
• TextView txtView = (TextView) findViewById(R.id.text_id);
• // -- change text size --
• txtView.setTextSize(24);
• return;
• }
• @Override
• public boolean onCreateOptionsMenu(Menu
menu) {
• // Inflate the menu; this adds items to the
action bar if it is present.
• getMenuInflater().inflate(R.menu.main,
menu);
• return true;
• }

• }
CheckBox

• One of the easiest and most common ways to


accept user input in an Android Application is
the Checkbox component.
• An on/off switch that can be toggled by the
user.
• You should use checkboxes when presenting
users with a group of selectable options that
are not mutually exclusive.
Android Radio Button
RadioButton
The RadioButton has two states: either
checked or unchecked.
RadioGroup
A RadioGroup is used to group together one
or more RadioButtons.
Spinner (Dropdown List)
• Spinner
A drop-down list that allows users to select one
value from a set.
3.3 Android application and activity
lifecycle
• Android devices have limited resources, therefore the
Android system is allowed to manage the available
resources by terminating running processes or recycling
Android components.
• Android platform supports lifecycle event which are called
in the case of process or component termination as well as
in case of a configuration change.
• The developer is responsible for maintaining the state of
the application.
• He is also responsible for restore the activity instance state.
• The application object is created whenever one of your
Android components are started
• It is started in a new process with a unique ID under a
unique user
• Even if you do not specify one in
your AndroidManifest.xml file, the Android system creates
a default object for you.
This object provides the following main lifecycle methods:
• onCreate() - called before the first components of the
application starts
• onLowMemory() - called when the Android system requests
that the application cleans up memory
• onTerminate() - only for testing, not called in production
• onConfigurationChanged() - called whenever the
configuration changes
• The application object starts before any component and
runs at least as long as another component of the
application runs.
• If the Android system needs to terminate processes it
follows the following priority system.
Process status Description Priority

Foreground An application in which the user is 1


interacting with an activity, or which
has an service which is bound to such
an activity. Also if a service is
executing one of its lifecycle methods
or a broadcast receiver which runs
its onReceive() method.

Visible User is not interacting with the 2


activity, but the activity is still
(partially) visible or the application
has a service which is used by a
inactive but visible activity.

Service Application with a running service 3


which does not qualify for 1 or 2.

Background Application with only stopped 4


activities and without a service or
executing receiver. Android keeps
them in a least recent used (LRU) list
and if requires terminates the one
which was least used.

Empty Application without any active 5


components.
Activity lifecycle
• The Android system is also allowed to recycle Android
components to free up resources
Activity state:
• Running: Activity is visible and interacts with the user.
• Paused:Activity is still visible but partially obscured,
instance is running but might be killed by the system.
• Stopped: Activity is not visible, instance is running but
might be killed by the system.
• Killed:Activity has been terminated by the system of by
a call to its finish() method.
• The Android system defines a lifecycle for activities via
predefined (lifecycle) methods.
• The most important methods are:
• onCreate(): Called then the activity is created. Used to
initialize the activity, for example create the user interface.
• onResume(): Called if the activity get visible again and the
user starts interacting with the activity again. Used to
initialize fields, register listeners, bind to services, etc.
• onPause(): Called once another activity gets into the
foreground. Always called before the activity is not visible
anymore. Used to release resources or save application data.
For example you unregister listeners, intent receivers, unbind
from services or remove system service listeners.
• onStop(): Called once the activity is no longer visible. Time or
CPU intensive shut-down operations, such as writing
information to a database should be down in
the onStop() method.
• This method is guaranteed to be called as of API 11.
• The life cycle of an activity with its most important methods is
displayed in the following diagram.

You might also like