0% found this document useful (0 votes)
31 views35 pages

Open Book Chapter 1 - 6

This document provides an overview of mobile applications and Android layout design. It defines native and hybrid mobile apps, and explains that native apps are developed specifically for a mobile OS while hybrid apps are web apps packaged in a native wrapper. It also discusses different Android layout techniques including declaring UI elements in XML or programmatically, and explains benefits of using XML such as separating presentation from behavior. Finally, it covers XML fundamentals such as being well-formed, namespaces, and special characters that must be encoded.

Uploaded by

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

Open Book Chapter 1 - 6

This document provides an overview of mobile applications and Android layout design. It defines native and hybrid mobile apps, and explains that native apps are developed specifically for a mobile OS while hybrid apps are web apps packaged in a native wrapper. It also discusses different Android layout techniques including declaring UI elements in XML or programmatically, and explains benefits of using XML such as separating presentation from behavior. Finally, it covers XML fundamentals such as being well-formed, namespaces, and special characters that must be encoded.

Uploaded by

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

CHAPTER 1

What is a Mobile Application?

 Application Software Designed to Run on A Mobile Device

NATIVE APP

 A native app is a smartphone application developed specifically for a mobile operating


system (think Objective-C or Swift for iOS vs. Java for Android).

 Since the app is developed within a mature ecosystem following the technical and user
experience guidelines of the OS, it not only has the advantage of faster performance but also
“feels right”.

 What feeling right means is that the in-app interaction has a look and feel consistent with
most of the other native apps on the device. The end user is thus more likely to learn how to
navigate and use the app faster.

HYBRID APP

 Hybrid applications are, at core, websites packaged into a native wrapper.

 A hybrid app is a web app built using HTML5 and JavaScript, wrapped in a native container
which loads most of the information on the page as the user navigates through the
application (Native apps instead download most of the content when the user first installs
the app).
MVC – MODEL(JAVA), CONTROLLER (ANDROID ACTIVITY), VIEW (XML)

MOBILE APPLICATION – ONE, TWO AND THREE LAYERS


CHAPTER 2

ANDROID LAYOUT DESIGN

► A layout defines the structure for a user interface in your android 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 ViewGroup is an
invisible container that defines the layout structure for View and other ViewGroup objects.

► In android application development, we 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. You can also use Android
Studio’s Layout Editor to build your XML layout using drag-and-drop interface.

► Instantiate layout elements at runtime. Your app can create View and ViewGroup
objects (and manipulate their properties) programmatically.
CREATE PROGRAMMATICALLY XML

WHY XML (EXTENSIBLE MARKUP LANGUAGE)?

► Declaring your UI in XML allows you to separate the presentation of your app from the code
that controls its behavior. Using XML files also makes it easy to provide different layouts for
different screen sizes and orientations

WHAT IS XML (EXTENSIBLE MARKUP LANGUAGE)?

► XML is a set of rules for forming semantic tags that break a document into parts and identify
the different parts of the document.

► XML, is a metamarkup language, in which you make up the tags you need as you go along.

► These tags must be organized according to certain general principles, but they're quite
flexible in their meaning.

► For instance, if you're working on genealogy and need to describe people, births, deaths,
burial sites, families, marriages, divorces, and so forth, you can create tags for each of these
elements.

WHAT IS MARKUP LANGUAGE (ML)?

■ A markup language is a combination of words and symbols which give instructions


on how a document should appear.

■ For example, a tag may indicate that words are written in italics or bold type.

■ Although the most common and most widely used markup languages are written for
computers, the concept of a markup language is not limited to computer
programming.
SGML

■ The first drive for XML was, the Standard Generalized Markup Language (SGML).

■ SGML is an international standard for semantic tagging of documents that's been around for
a little over a decade.

■ SGML is intended for semantic markup that assists computer cataloging and indexing, and
can be extended in an infinite variety of ways to handle new data formats.

■ Although SGML has its advantages, it is too complex and expensive for anyone to put their
information on the Internet.

WHAT IS SGML?

■ SGML (Standard Generalized Markup Language) is a standard for how to specify a


document markup language or tag set.

■ SGML is not in itself a document language, but a description of how to specify one.

■ It is metadata

HTML

■ HTML, invented by Tim Berners-Lee at CERN in 1990, HTML was designed as a simple
replacement for SGML that could be written without the assistance of expensive authoring
tools.

■ Unfortunately, HTML didn't scale very well.

■ First of all, it was limited to a small fixed set of tags.

■ HTML lacked the flexibility and adaptability of SGML.

■ HTML is probably the most widely used markup language in history.

■ Both SGML and HTML have shortcomings, and a new approach was needed to combine their
strengths without their limitations XML.
WHAT IS HTML?

■ HTML (Hypertext Markup Language) is the set of markup symbols or codes inserted
in a file intended for display on a World Wide Web browser page.

■ The markup tells the Web browser how to display a Web page's words and images
for the user.

■ Each individual markup code is referred to as an element (but many people also
refer to it as a tag).

SGML

SGML is semantic markup for storage


(define your own tags).

XML

XML is semantic markup for


interoperability (define your
own tags).

HTML

HTML is visual markup for presentation


(predefined tags).

WHY USE XML?

■ Separate data from HTML

■ Simplify data sharing

■ Simplify data transport

■ Simplify Platform Changes

■ Makes data more available

A WELL-FORMED DOCUMENT MUST HAVE TO THE FOLLOWING RULES:


A well-formed XML document means that the document is syntactically correct

This allows it to be processed by generic processors (XML parser) that traverse the
document and create an internal tree representation.

Every start tag has a matching end tag.

Elements may nest, but must not overlap.

There must be exactly one root element.

Attribute values must be quoted.

An element may not have two attributes with the same name.

Comments and processing instructions may not appear inside tags.

No unescaped < or & signs may occur inside character data.

ONLY WELL-FORMED DOCUMENTS CAN BE PROCESSED BY XML PARSERS.

WELL-FORMED XML DOCUMENTS

Every start tag has a matching end tag.

Eg: <name> ... </name>

But empty elements can be abbreviated: <break />.

XML tags are case sensitive

The tag <Student> is different from the tag <student>

start with letters (including non-Latin characters) or the” _" character, but not
numbers or other punctuation characters.                  

After the first character, numbers are allowed, as are the characters "-" and ".".

Names can't contain spaces.                              

Names can't contain the ":" character.

Names can't start with the letter’s "xml", in uppercase, lowercase, or mixed – you can't start a
name with "xml", "XML", "XmL", or any other combination.

Elements may nest, but must not overlap.

e.g. not <b><i>bold and italic</b></i> (not valid)

Attribute values must be quoted.

e.g. <time unit="days">

There must be exactly one root element.

<root>
<child>
<subchild>..</subchild>
<subchild>..</subchild>
</child>

An element may not have two attributes with the same name.

e.g. <time unit="days“ unit=“hour”>

Comments and processing instructions may not appear inside tags.

Example comment <!– This is comment -->

No unescaped < or & signs may occur inside character data.

E.g. <comparison>6 is < 7 & 7 > 6</comparison>

A document that obeys all the rules is said to be well-formed.

Being well-formed is the minimum requirement for being an XML document.

FIVE SPECIAL CHARACTERS MUST BE WRITTEN AS ENTITIES:

&amp; for & (almost always necessary)

&lt; for < (almost always necessary)

&gt; for > (not usually necessary)

&quot; for " (necessary inside double quotes)

&apos; for ' (necessary inside single quotes)

These are the only predefined entities in XML

NAMESPACES AND URIS*

A namespace is defined as a unique string


To guarantee uniqueness, typically a URI (Uniform Resource Indicator) is used, because
the author “owns” the domain

It doesn't have to be a “real” URI; it just has to be a unique string

Example: http://www.matuszek.org/ns

There are two ways to use namespaces:

Declare a default namespace

Associate a prefix with a namespace, then use the prefix in the XML to refer to the
namespace

NAMESPACE SYNTAX*

In any start tag you can use the reserved attribute name xmlns:

<book xmlns="http://www.matuszek.org/ns">

This namespace will be used as the default for all elements up to the corresponding end
tag

You can override it with a specific prefix

You can use almost this same form to declare a prefix:

<book xmlns:dave="http://www.matuszek.org/ns">

Use this prefix on every tag and attribute you want to use from this namespace,
including end tags--it is not a default prefix

<dave:chapter dave:number="1">To Begin</dave:chapter>

You can use the prefix in the start tag in which it is defined:

<dave:book xmlns:dave="http://www.matuszek.org/ns">

COMMENTS

<!-- This is a comment in both HTML and XML -->

Comments can be put anywhere in an XML document

Comments are useful for:

Explaining the structure of an XML document

Commenting out parts of the XML during development and testing

Comments are not elements and do not have an end tag

CHAPTER 3

WHAT IS ANDROID?
● Android is a Linux-based platform for mobile devices.

● Android is a mobile operating system based on a modified version of the Linux kernel and
other open source software, designed primarily for touchscreen mobile devices such as
smartphones and tablets.

● What kind of mobile devices?

MOBILE.TABLETS, EREADERS, GOOGLE GLASSES AND ANDROID TV

ANDROID SOFTWARE DEVELOPER KIT (SDK)

• Development tools (debugger, monitors, editors)

• Libraries (maps, wearables)

• Virtual devices (emulators)

• Documentation (developers.android.com)

• Sample code

ANDROID STUDIO

• Official Android IDE

• Develop, run, debug, test, and package apps

• Monitors and performance tools

• Virtual devices

• Project views

• Visual layout editor

THE ANDROID ARCHITECTURE


Built on top of Linux
kernel (v. 2.6-3.0)
Advantages:

 Portability (i.e. easy to


compile on different
hardware architectures)
 Security (e.g. secure multi-
process environment)
 Provides memory
management, process
management, security model,
networking and lot of core OS
infrastructure

Dalvik Virtual
Native Libraries
Machine (VM)
(C/C++ code)
 Novel Java Virtual
 Graphics (Surface Machine
Manager)
implementation (not
 Multimedia (Media
Framework)
using the Oracle
 Database DBMS JVM)
(SQLite)  Open License (Oracle
 Font Management JVM is not open!)
(FreeType)  Optimized for
 WebKit memory-constrained
 C libraries (Bionic) devices
 ….  Faster than Oracle
JVM
 ….

Linux Kernel

● Threading and low-level memory management

● Security features

● Drivers

C/C++ libraries

● Core C/C++ Libraries give access to core native Android system components and services.

Android runtime
● Each app runs in its own process with its own instance of the Android Runtime.

DALVIK VM

• All applications written in Java are converted to the dalvik executable .dex

• Every android app runs its own process, with its own instance of the dalvik virtual machine

• Not a traditional JVM, but a custom VM designed to run multiple instances efficiently on a
single device

• VM uses linux kernel to handle low-level functionality incl. security, threading, process and
memory management

Application
Framework
(Core Components of
Android)

 Activity Manager
 Packet Manager
 Telephony Manager
 Location Manager
 Contents Provider
 Notification
Manager
 ….

Applications
(Written in Java code)

 Android Play Store


 Entertainment
 Productivity
 Personalization
 Education
 Geo-communication
 ….

JAVA API FRAMEWORK


The entire feature-set of the Android OS is available to you through APIs written in the Java
language.

● View class hierarchy to create UI screens

● Notification manager

● Activity manager for life cycles and navigation

APPLICATION FRAMEWORK

● Rich, extensible set of Views

- apps can include lists, grids, text boxes, buttons, web browser

● Content Providers

- allows data access from other applications or share own data

● Resource Manager

- access to localized strings, graphics, layout files

● Notification Manager

- enables custom alerts to be displayed in status bar

● Activity Manager

- Manages lifecycle of applications and provides navigation backstack

APPLICATIONS

• All apps (native and 3rd party) are written using the same APIs and run on the same run time
executable

• All apps have APIs for hardware access, location-based services, support for background
services, map-based activities, 2D and 3D graphics.

WHAT IS ANDROID APP??

● One or more interactive screens

● Written using Java Programming Language and XML

● Uses the Android Software Development Kit (SDK)

● Uses Android libraries and Android Application Framework

● Executed by Android Runtime Virtual machine (ART / DVM)

CHALLENGE OF ANDROID DEVELOPMENT


● Multiple screen sizes and resolutions

● Performance: make your apps responsive and smooth

● Security: keep source code and user data safe

● Compatibility: run well on older platform versions

● Marketing: understand the market and your users


(Hint: It doesn't have to be expensive, but it can be.)

APP BUILDING BLOCKS

● Resources: layouts, images, strings, colors as XML and media files

● Components: activities, services, and helper classes as Java code

● Manifest: information about app for the runtime

● Build configuration: APK versions in Gradle config files

CHAPTER 4
APP COMPONENTS

• Core building blocks of an app.

• Entry points for an app.

• Activities are “screens” with a UI.

• Services run a task in the background.

• Broadcast receivers deliver events to apps outside of regular user flow.

• Content providers manage a pool of information.

ACTIVITIES

• A single screen with a user interface.

• Most apps have multiple independent activities.

• E-mail: Show messages, compose, read.

• If allowed, other apps can start any activity.

• Camera app opens “Compose” activity to share photo.

• Activities control and link processes.

• Ensure the current process is not killed.

• Link to calling activities and maintain their process.

• Model state in case process is killed.

• Model flow between apps.


SERVICES

• Entry point for running a background process.

• Playing music, sending files.

• Does not provide a direct UI.

• Can be started by an activity.

• Can maintain a notification to allow user interaction.

• Services without notifications can be killed if resources are needed by OS.

• Bound services offer an API to the calling app.

• Maintained as long as needed, then killed.

BROADCAST RECEIVER

• Allows OS to deliver events when the app is not running.

• Listen to system-wide broadcast announcements.

• Respond to events like a photo being taken.

• Often notify users that an event has occurred.

• Often minimal, used as a gateway to launch activities or services.

CONTENT PROVIDERS

• Manages a shared set of app data.

• Other, allowed, apps can query or modify the data.

• Android has a Content Provider for contact data.

• An entry point into an app for publishing data items.

• Identified by a URI.

• Owning app wakes up when a URI is accessed.

• URIs provide a secure way to pass content.

• Content is locked and accessed through temporary permission.

Designing Layout in Android

● All Android UI elements built using View and ViewGroup objects

● View is an object that draws something on the screen that the user can interact with

● ViewGroup is a container that holds Views and other ViewGroup objects and defines layout
of all or part of the screen

● Views and ViewGroups for a particular screen arranged into a hierarchy


USER INTERFACE LAYOUT

● ViewGroup is an invisible container that organizes child Views (some of which might
themselves be ViewGroups)

○ ViewGroup is a subclass of View!

● Child Views inside a ViewGroup are widgets or input controls that draw some part of the UI

● Make your UI no more complex than it needs to be

○ It takes more time and memory to construct and display a complex View hierarchy
● Declare your layout either

○ in code, by instantiating View objects and building a tree

○ in an XML layout file (PREFERRED!)

 Name of XML element for a View is the same as the class name of the View
(e.g., TextView, LinearLayout)

 Above is a simple vertical layout with a TextView and a Button

 When XML layout loaded, each node inflated into a runtime object

LAYOUT

● Layout defines visual structure of a user interface

○ e.g., for an Activity or an app widget

● You can declare Layouts either in your Java code or in an XML layout file

○ Can declare default layouts in XML

○ Modify state of UI components in your code


DECLARING UI in XML resource

● Declaring UI in XML resource lets you separate presentation from logic and behaviour

○ Can modify presentation without changing code

● Can create XML layouts for different screen orientations, sizes and densities or different
languages

● Easier to debug when layout defined in XML

DEFINING LAYOUT IN XML

● XML vocabulary for defining layouts follows naming of classes and methods

• XML element names correspond to class names

• XML attribute names correspond to methods

 Though there are a couple of small differences

 e.g., EditText.setText() corresponds to text attribute

WRITING AN XML LAYOUT FILE

● Each layout file contains one root element, which must be (i.e., correspond to) a View or a
ViewGroup object

• This will usually be a Layout

 Layout is a subclass of ViewGroup!

● The root element contains child elements which correspond to Views (often widgets) and
ViewGroups (often Layouts)

● The layout XML file should end with “.xml” and be stored in the res/layout/ directory
LOADING AN XML LAYOUT RESOURCE

● When app is compiled, each XML layout file is compiled into a View resource

● Load the layout by calling setContentView() from the onCreate() callback implementation in
your Activity class

● Pass setContentView() the id of the layout resource, as defined in the R.java file

● Example shows case for layout declared in main_layout.xml

ATTRIBUTES

● Each View and ViewGroup element in an XML layout file has its own set of attributes (e.g.,
id, text)

• These attributes are inherited by any class that subclasses View or ViewGroup

● Some attributes are layout parameters that describe layout orientations of a View object
(e.g., layout_width, layout_height)

ID

● Any View object may have an integer ID

● Assigned in id attribute as a string

○ Associated with an integer constant in R.java

● @: indicates the type of the value following the slash

○ in this case, an “id” type resource

● +: indicates that this is the first time the resource is being defined and that it should be
added to R.java
ANDROID RESOURCES

● You can also access a number of Android framework IDs

● Here you do not use the “+” symbol, since you are not defining the ID, just using one that
has already been defined

● You declare the type of the resource to be “@android:id” to indicate that the id is defined in
the android package namespace

○ “android” namespace means referencing a resource defined in android.R resources


class, not private resources class

CREATING AND REFERENCING VIEWS

● First define the view or widget in the layout file and assign a unique id

● Then create an instance of the View and capture it from the layout (usually in onCreate())

● ID should be unique throughout the entire View tree

LAYOUT PARAMETERS

● XML layout attributes with name layout_something define layout parameters

● A ViewGroup implements a nested class that extends ViewGroup.LayoutParams

○ i.e., a class called LayoutParams, defined inside ViewGroup

● The ViewGroup.LayoutParams class inside a ViewGroup defines size and position of each of
its child Views

● Every LayoutParams subclass has its own syntax for setting values

● Each child element must define LayoutParams appropriate for its parent
● A child ViewGroup may also define different LayoutParams for its own children

LAYOUT_WIDTH AND LAYOUT_HEIGHT

● Every ViewGroup.LayoutParams defines a width (layout_width) and height (layout_height)

○ Every view in the ViewGroup must define these in its XML declaration

● Many ViewGroups also include optional margins and borders

● layout_width and layout_height can be defined by absolute distances (DISCOURAGED!)

● Usually define layout_width and layout_height using a constant such as

○ wrap_content – View expands to size of content

○ fill_parent or match_parent – View as big as parent will allow

● Can also use density-independent pixel units (dp)


LAYOUT POSITION

● View controls a rectangular area in the UI

● View has left, top, width and height properties, expressed in pixels relative to the parent

● Has getter methods: getLeft(), getTop(), getWidth(), getHeight()

SIZE, PADDING AND MARGINS OF A VIEW

● getWidth(), getHeight()

○ actual width and height of View on screen at drawing time after layout

● getMeasuredWidth(), getMeasuredHeight()

○ how big a view wants to be within its parent

● setPadding(), getPaddingLeft(), getPaddingTop(), getPaddingRight(), getPaddingBottom()

○ pixels of padding between contents of view and edge of its rectangle

● ViewGroups can be used to define margins

COMMON LAYOUTS
LINEARLAYOUT

● LinearLayout is a ViewGroup that aligns all its children in a single row or column

● Direction specified with android:orientation attribute

● Horizontal list will be height of the tallest element

● Vertical list will be width of the widest element

● LinearLayout respects margins between children and gravity of each child

○ gravity is right, center, or left alignment

LINEARLAYOUT EXAMPLE
RELATIVELAYOUT

● RelativeLayout displays children in positions relative to each other (siblings)...

○ e.g., “left-of” or “below” a sibling

● ...or relative to the parent RelativeLayout area

○ e.g., aligned to the bottom, left of centre

● RelativeLayout can eliminate nested ViewGroups and keep the View hierarchy flat

○ improves performance!

● Can sometimes replace several nested LinearLayouts with a single RelativeLayout

POSITIONING VIEWS

● RelativeLayout lets child views specify their positions relative to each other and the
containing Layout

○ e.g., align two elements by right border, make one below another, centered in the
screen, centered left, etc.

● By default, all child Views drawn in the top-left of the layout

● Define positions using layout properties available from RelativeLayout.LayoutParams

EXAMPLES OF LAYOUT PROPERTIES

● android:layout_alignParentTop

○ if “true” then top edge of View matches top edge of parent

● android:layout_centerVertical

○ if “true”, child centered vertically in parent

● android:layout_below

○ Top edge of this View below View specified with resource ID

● android:layout_toRightOf

○ Left edge of this View to the right of View specified with resource ID

● There are many more RelativeLayout layout attributes!


EXAMPLE OF RELATIVELAYOUT

CHAPTER 5

WHAT IS AN ACTIVITY?

● An Activity is an application component

● Represents one window, one hierarchy of views

● Typically fills the screen, but can be embedded in other Activity or a appear as floating
window

● Java class, typically one Activity in one file

WHAT DOES AN ACTIVITY DO?

● Represents an activity, such as ordering groceries, sending email, or getting directions

● Handles user interactions, such as button clicks, text entry, or login verification

● Can start other activities in the same or other apps

● Has a life cycle—is created, started, runs, is paused, resumed, stopped, and destroyed
IMPLEMENTING ACTIVITIES

1. Define layout in XML

<?xml version="1.0" encoding="utf-8"?>


<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Let's Shop for Food!" />
</RelativeLayout>

2. Define Activity Java class

public class MainActivity extends AppCompatActivity {

@Override

protected void onCreate(Bundle savedInstanceState)

super.onCreate(savedInstanceState);

3. CONNECT ACTIVITY WITH LAYOUT


public class MainActivity extends AppCompatActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
}

4. Declare activity in Android manifest


<activity android:name=".MainActivity">

5. Declare main activity in manifest


MainActivity needs to include intent-filter to start from launcher
<activity android:name=".MainActivity">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
START AN ACTIVITY WITH AN EXPLICIT INTENT

To start a specific Activity, use an explicit Intent

1. Create an Intent
○ Intent intent = new Intent(this, ActivityName.class);
2. Use the Intent to start the Activity
○ startActivity(intent);

START AN ACTIVITY WITH IMPLICIT INTENT

To ask Android to find an Activity to handle your request, use an implicit Intent

1. Create an Intent

○ Intent intent = new Intent(action, uri);

2. Use the Intent to start the Activity

○ startActivity(intent);

SENDING AND RECEIVING DATA

Two types of sending data with intents

● Data—one piece of information whose data location can be represented by an URI

● Extras—one or more pieces of information as a collection of key-value pairs in a Bundle

In the first (sending) Activity:

1. Create the Intent object

2. Put data or extras into that Intent

3. Start the new Activity with startActivity()

In the second (receiving) Activity:

1. Get the Intent object, the Activity was started with

2. Retrieve the data or extras from the Intent object

Put information into intent extras

● putExtra(String name, int value)


⇒ intent.putExtra("level", 406);

● putExtra(String name, String[] value)


⇒ String[] foodList = {"Rice", "Beans", "Fruit"};
intent.putExtra("food", foodList);

● putExtras(bundle);
⇒ if lots of data, first create a bundle and pass the bundle.
SENDING DATA TO AN ACTIVITY WITH EXTRAS

public static final String EXTRA_MESSAGE_KEY =


"com.example.android.twoactivities.extra.MESSAGE";

Intent intent = new Intent(this, SecondActivity.class);

String message = "Hello Activity!";

intent.putExtra(EXTRA_MESSAGE_KEY, message);

startActivity(intent);

GET DATA FROM INTENTS

getData();
⇒ Uri locationUri = intent.getData();

int getIntExtra (String name, int defaultValue)


⇒ int level = intent.getIntExtra("level", 0);

Bundle bundle = intent.getExtras();


⇒ Get all the data at once as a bundle.

RETURNING DATA TO THE STARTING ACTIVITY

1. Use startActivityForResult() to start the second Activity

2. To return data from the second Activity:

● Create a new Intent

● Put the response data in the Intent using putExtra()

● Set the result to Activity.RESULT_OK


or RESULT_CANCELED, if the user cancelled out

● call finish() to close the Activity

3. Implement onActivityResult() in first Activity


STARTACTIVITYFORRESULT()

startActivityForResult(intent, requestCode);

● Starts Activity (intent), assigns it identifier (requestCode)

● Returns data via Intent extras

● When done, pop stack, return to previous Activity, and execute onActivityResult() callback to
process returned data

● Use requestCode to identify which Activity has "returned"

STARTACTIVITYFORRESULT() EXAMPLE

public static final int CHOOSE_FOOD_REQUEST = 1;

Intent intent = new Intent(this, ChooseFoodItemsActivity.class);

startActivityForResult(intent, CHOOSE_FOOD_REQUEST);

RETURN DATA AND FINISH SECOND ACTIVITY

// Create an intent

Intent replyIntent = new Intent();

// Put the data to return into the extra

replyIntent.putExtra(EXTRA_REPLY, reply);

// Set the activity's result to RESULT_OK

setResult(RESULT_OK, replyIntent);

// Finish the current activity

finish();

IMPLEMENT ONACTIVITYRESULT()

public void onActivityResult(int requestCode,

int resultCode, Intent data) {

super.onActivityResult(requestCode, resultCode, data);

if (requestCode == TEXT_REQUEST) { // Identify activity

if (resultCode == RESULT_OK) { // Activity succeeded

String reply = data.getStringExtra(SecondActivity.EXTRA_REPLY);


// … do something with the data

}}}

ACTIVITY STACK

● When a new Activity is started, the previous Activity is stopped and pushed on the Activity
back stack

● Last-in-first-out-stack—when the current Activity ends, or the user presses the Back button,
it is popped from the stack and the previous Activity resumes

TWO FORMS OF NAVIGATION

Temporal or back navigation

● provided by the device's Back button

● controlled by the Android system's back stack

Ancestral or up navigation

● provided by the Up button in app's action bar

● controlled by defining parent-child relationships between activities in the Android manifest

BACK NAVIGATION

● Back stack preserves history of recently viewed screens

● Back stack contains all the Activity instances that have been launched by the user in reverse
order for the current task

● Each task has its own back stack

● Switching between tasks activates that task's back stack

UP NAVIGATION

● Goes to parent of current Activity

● Define an Activity parent in Android manifest

● Set parentActivityName

<activity

android:name=".ShowDinnerActivity"

android:parentActivityName=".MainActivity" >

</activity>
ACTIVITY STATES AND APP VISIBILITY

● Created (not visible yet)

● Started (visible)

● Resume (visible)

● Paused (partially invisible)

● Stopped (hidden)

● Destroyed (gone from memory)

State changes are triggered by user action, configuration changes such as device rotation, or system
action

CALLBACKS AND WHEN THEY ARE CALLED

onCreate(Bundle savedInstanceState)—static initialization

onStart()—when Activity (screen) is becoming visible

onRestart()—called if Activity was stopped (calls onStart())

onResume()—start to interact with user

onPause()—about to resume PREVIOUS Activity

onStop()—no longer visible, but still exists and all state info preserved

onDestroy()—final call before Android system destroys Activity

ACTIVITY STATES AND CALLBACKS GRAPH


WHEN DOES CONFIG CHANGE?

Configuration changes invalidate the current layout or other resources in your activity when the
user:

● Rotates the device

● Chooses different system language, so locale changes

● Enters multi-window mode (from Android 7)

WHAT HAPPENS ON CONFIG CHANGE?

On configuration change, Android:

1. Shuts down Activity


by calling:

● onPause()

● onStop()

● onDestroy()

2. Starts Activity over again


by calling:

● onCreate()

● onStart()

● onResume()

CHAPTER 6

ACCEPTING USER INPUT

● Freeform text and numbers: EditText (using keyboard)

● Providing choices: CheckBox, RadioButton, Spinner

● Switching on/off: Toggle, Switch

● Choosing value in range of values: SeekBar

CLICKABLE VERSUS FOCUSABLE

Clickable—View can respond to being clicked or tapped

Focusable—View can gain focus to accept input

Input controls such as keyboards send input to the view that has focus
WHICH VIEW GETS FOCUS NEXT?

● Topmost view under the touch

● After user submits input, focus moves to nearest neighbor—priority is left to right, top to
bottom

● Focus can change when user interacts with a directional control

SET FOCUS EXPLICITLY

Use methods of the View class to set focus

● setFocusable() sets whether a view can have focus

● requestFocus() gives focus to a specific view

● setOnFocusChangeListener() sets listener for when view gains or loses focus

● onFocusChanged() called when focus on a view changes

FIND THE VIEW WITH FOCUS

● Activity.getCurrentFocus()

● ViewGroup.getFocusedChild()

COMMON INPUT TYPES

● textCapCharacters: Set to all capital letters

● textCapSentences: Start each sentence with a capital letter

● textPassword: Conceal an entered password

● number: Restrict text entry to numbers

● textEmailAddress: Show keyboard with @ conveniently located

● phone: Show a numeric phone keypad

● datetime: Show a numeric keypad with a slash and colon for entering the date and time
TEXTVIEW FOR TEXT

● TextView is View subclass for single and multi-line text

● EditText is TextView subclass with editable text

● Controlled with layout attributes

● Set text:

○ Statically from string resource in XML

○ Dynamically from Java code and any source

FORMATTING TEXT IN STRING RESOURCE

● Use <b> and <i> HTML tags for bold and italics. All other HTML tags are ignored

● String resources: one unbroken line = one paragraph. \n starts a new a line or paragraph

● Escape apostrophes and quotes with backslash (\", \’). Escape any non-ASCII characters with
backslash (\)

CREATING TEXTVIEW IN XML

<TextView android:id="@+id/textview"

android:layout_width="match_parent"

android:layout_height="wrap_content"

android:text="@string/my_story"/>

COMMON TEXTVIEW ATTRIBUTES

android:text—text to display

android:textColor—color of text

android:textAppearance—predefined style or theme

android:textSize—text size in sp

android:textStyle—normal, bold, italic, or bold|italic

android:typeface—normal, sans, serif, or monospace

android:lineSpacingExtra—extra space between lines in sp

You might also like