95
Welcome to Android!

Welcome to Android!. Let’s review what we know about the web Structure is _________ Presentation is ___________ Behavior is ___________ HTML CSS JavaScript

Embed Size (px)

Citation preview

Welcome to Android!

Let’s review what we know about the web

• Structure is _________

• Presentation is ___________

• Behavior is ___________

HTML

CSS

JavaScript

In Android

• Structure is _________

• Presentation is ___________

• Behavior is ___________

HTML

CSS

JavaScript

XML

XML

Java

Web Review

• HTML has specific elements for certain jobs– <p> for non editable text– <h1-h6> header– <li> for list items

• HTML has specific elements to contain other elements– <div>, <header>, <footer>, <table>, <nav>– <span>– <ol>/<ul>

Android

• Android has certain elements for certain jobs as well.

• In Android, we call these elements Views

• Android also has specific elements to contain other elements

• In Android, we call these elements View Groups

When the HTML document gets loaded what object is created?

<body> <div id="box1" class="box">1</div>

<div id="box2" class="box">2</div><div id="box3" class="box">3</div><div id="box4" class="box">4</div>

</body>

body

div#box1 div#box2 div#box3 div#box4

Android XML Layout<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" >

<TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" />

<Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" />

</LinearLayout>

Android XML Layout<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" >

<TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" />

<Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" />

</LinearLayout>

LinearLayout

TextView Button

In Android Lingo, the DOM is known as the View Hierarchy

Web Review

Using the DOM, how do we find elements?1. ID2. Class3. Tag4. Attribute5. Traversing the DOM tree (firstChild, parent,

children, etc.)

In Android

We find views by• ID• Traversing the View Hierarchy

What is Android?

• A software stack for mobile devices that includes an operating system, middleware, and key applications.

• Uses large parts of the Java API– Doesn’t use Swing or AWT

• Uses XML to declare layouts

• Supports SQLite

• Awesome!

Android OS Versions

Platform Version Codename

1.5 Cupcake

1.6 Donut

2.1 Éclair

2.2 Froyo

2.3 Gingerbread

3.0 Honeycomb (First version to support tablets)

4.0 Ice Cream Sandwich (Merges Gingerbread and Honeycomb)

4.1 – 4.3 Jelly Bean

4.4 Kit Kat

5.0 Lollipop (just released!)

Android Toolkit

• Eclipse is the premier IDE for developing Android.– Integrates the Android SDK for easy building,

virtual device creation, and more.

• Android apps can be built with Apache Ant; therefore, you could use any text editor of your preference.

Eclipse HotkeysKey Shortcut Action

Ctrl + O Show Outline. Uses intellisense to quickly navigate and find class members and methods.

Ctrl + Shift + O Add and Organize Imports

Ctrl + Shift + C Toggle Comment Block

Run/Debug

Ctrl + F11 Run last launched

F11 Debug last launched

F5 Step into

F6 Step over

F7 Step return

F8 Resume

Eclipse Perspectives

• Eclipse “Perspectives” determine the visible actions and views within a window/tab.

• For Android there are 3 important “Perspectives”: 1. Java2. Debugging3. DDMS

Java Perspective

• This is the window where you will do the majority of your coding.

Debugging Perspective

• This is the default debugging tool built into Eclipse. Very similar to other debuggers (Netbeans, Visual Studio, etc).

• Allows the ability to set break points in code and pause the application’s execution and step through code line by line.

• Allows the ability to view a variable’s value(s) in real time, step into functions, etc.

Debugging Perspective

DDMS Perspective

• Usually the place for “advanced” features. • Provides info for:

1. Devices • Shows connected Android devices and emulators

2. Emulator Control • Change network state, speed, latency• Spoof calls or SMS text messages• Set location of phone

3. Logcat• Outputs messages that you print out using the Log class along with other system

messages such as stack traces when exceptions are thrown.

DDMS Perspective

Logging Messages in Android

• System.out.println does not work like in regular Java programs.

• Instead make use of the Log class.

Logging in Android

• Log.d(String tag, String msg) – Send a DEBUG log message.

• Log.e(String tag, String msg) – Send an ERROR log message.

• Log.i (String tag, String msg) – Send an INFO log message.

• Log.v (String tag, String msg) – Send a VERBOSE log message.

• Log.w(String tag, String msg) – Send a WARN log message.

Logging in Android

• In the DDMS Perspective, inside the Logcat window, you can filter Log messages.

• You can filter log messages to reduce “noise” and only see certain types of Log messages.

Filtering Log Messages

1. By TAG – the first parameter of Log method

2. By type:• DEBUG• ERROR• INFO• VERBOSE• WARN

Log Example

This Log message could be filtered either by adding a filter for “INFO” Log messages or by adding a filter for the “HelloWorld” tag.

Log Documentation• See http://developer.android.com/reference/android/util/Log.html for more

details.

What makes an Android App?

Most Apps Consists of• Android manifest• Activities• Views• Event logic for user interaction• XML for defining layout, widgets, shapes, and colors• OpenGL ES 1.1 or 2.x GLSurfaceView or Skia Canvas

(android.graphics) if creating your own widgets.• SQL Lite database• JSON or XML for data to and from servers

Main components of an Android App

• Android Manifest• Activities• Views• Application Resources• Application Logic

Android Manifest

• Presents essential information about the application to the Android system. The system must have this info before running any of the application’s code.

1

Android Manifest’s role

1. Names the Java package for the application.

2. Declares permissions the application must have in order to operate.• Access to the internet• Access user’s contact data• Read/write to system settings.• Etc.

Android Manifest’s role

3. Declares the minimum level of the Android API the application requires to run.

4. Specify application icon and title

5. Describes the components of the application• Activities• Services• Broadcast receivers• Content provider

Android Manifest Example

Android Manifest Documentation

• http://developer.android.com/guide/topics/manifest/manifest-intro.html

What is an Android Activity

• An activity is a single, focused thing that the user can do.

• Activities in the system are managed as an activity stack (LIFO).

• An application consists of at least 1 Activity, but can have many.

Activity

• Android Apps don’t have the main() paradigm. – Unlike C, C++, Java, etc.

• Instead, Android uses an Activity for the code execution starting point of an application.

• Activities have an important life cycle which every Android developer should know!!!

2

Activity Lifecycle

Activity Lifecycle onCreate()

• An activity is created when a user launches an application.

• The Activity’s onCreate() is the very first method called. Think of it as main().

• Use this method for basic startup logic that should happen only once for the entire lifecycle.

onCreate() startup logic

• Create User Interface components dynamically or from resources.

• Initialize class scope variables.

• Get a reference to an object that was inflated from XML.

Activity Lifecycle onStart()

• Your application becomes visible

Activity Lifecycle onResume()

• The activity is visible and running

• Your activity will remain in this state until:– A new application starts (receive a phone call)– User navigates to a new activity (back key)– The device screen turns off

• Use this method to resume anything that was stopped or paused.

Activity Lifecycle onPause()

• Happens when your activity is partially hidden. (Pop-up Window)

• As long as your activity is partially visible but not in focus, you’re paused.

• Use this method to pause ongoing actions (video, music, animation, etc.), save state, and release system resources.

Activity Lifecycle onStop()

• Happens when your activity is no longer visible.

• Use this method to 1. release all system resources that aren’t needed

while hidden2. write information to a database

Resume from Pause & Restart from Stopped

Activity Lifecycle onStop()

• While your activity is stopped, your application is kept in memory.

• If the OS runs out of memory while your application is stopped, it may be destroyed.

Stop to destroy

Activity Lifecycle onDestroy()

• Called when the system destroys your activity.

• By now you should have released all application resources in onPause() and onStop(), so you shouldn’t have to do much here.

• This method is not guaranteed to be called, so you shouldn’t rely on it.

Activity Lifecycle

• Once your activity is destroyed, all hope is not lost.

• When your app is paused you have the opportunity to save temporary state into a blob.

• When the system tries to resume your application, the blob is used to restore your application to the state is was in when it was paused.

Recreated after getting destroyed

Views

• Views are “widgets” that appears on the screen.

• Similar to HTML element

• Each View has predetermined characteristics, use cases, and attributes.

3

Two Basic View Types

View • Base class for widgets • Used to create interactive UI components.

– Button– Textfield– Image

ViewGroup• Base class for layouts • Serve as containers that hold others Views or other ViewGroups • Define layout properties.• Have unique characteristics for how they position children (grid,

horizontally, vertically, list, etc)

Similarities to HTML : View

• HTML has predefined widget elements:– <img>– <p>– <input>

• Android has predefined widget Views:– <ImageView>– <TextView>– <EditText>

Similarities to HTML: ViewGroup

• HTML has predefined container elements:– <body>– <div>– <span>

• Android has predefined container ViewGroups:– <FrameLayout>– <LinearLayout>– <RelativeLayout>– <GridLayout>

Views

Android Documentation for Input Controls

• http://developer.android.com/guide/topics/ui/controls.html

ViewGroups

ViewGroups

ViewGroup Documention

• http://developer.android.com/guide/topics/ui/declaring-layout.html

Creating Views

Views can be created 2 ways:1. Declaratively in XML2. Programmatically in code at runtime

Benefits of Declarative UI

If possible, Android documentation strongly recommends using the declarative approach for the following reasons:1. Helps separate the presentation of your application from the code that

controls its behavior.

2. UI declared in XML is external to your application code, which means that you can modify or adapt it without having to modify your source code and recompile.

3. Easier to visualize the structure of your UI.

4. Promotes clean code.

Declarative UI Example<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" >

<TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" />

<Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" />

</LinearLayout>

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" >

<TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" />

<Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" />

</LinearLayout>

XML Prolog

XML Namespace

You NEED to include the android namespace

<?xml version="1.0" encoding="utf-8"?><LinearLayout http://schemas.android.com/apk/res/android:layout_width="match_parent" http://schemas.android.com/apk/res/android:layout_height="match_parent" http://schemas.android.com/apk/res/android:orientation="vertical" >

<TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" />

<Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" />

</LinearLayout>

<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" >

<TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" />

<Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Button" /></LinearLayout>

Doctype

XML Namespace

Element

Attribute

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

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" >

<TextView android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="TextView" />

<Button android:id="@+id/button1" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text=“@string/button_text" />

</LinearLayout>

ViewGroup

View

View

HTML Translation

<div> <p id="sampleText">This is some text</p> <input id="sampleButton" type="button" value="Click Me!"/></div>

View Attributes : ID

XML Attributeandroid:id

DescriptionAn identifier name for a View. Use a View’s id to easily retrieve the View object in code.

Suggested ValuesFor id values, use a lower case with underscore naming convention.

Exampleandroid:id =“@+id/my_view”

@+id/ explanation

• Take another look at the previous exampleandroid:id="@+id/my_view“

• Notice the following:– The at-symbol (@) – The plus-symbol (+)

At-symbol (@)

• @ indicates that the Android XML parser should resolve the string with a resource.

• Behind the scenes Android will take android:id="@+id/my_view" and extract the my_view string and resolve to an ID resource. (Sounds confusing, but I’ll explain.)

Plus-symbol (+)

• + indicates that you’re creating a new resource name that should be added to the resources.

• Only worry about the plus-symbol with id resources.

• When referencing an existing resource ID, you do not need the plus-symbol.

To plus and not to plus!<?xml version="1.0" encoding="utf-8"?><RelativeLayout    xmlns:android="http://schemas.android.com/apk/res/android"    android:layout_width="fill_parent"    android:layout_height="wrap_content">    <TextView android:id="@+id/label"        android:layout_width="wrap_content"        android:layout_height="wrap_content"        android:text="URL:"        android:layout_alignBaseline="@+id/entry"        android:layout_alignParentLeft="true"/>    <EditText        android:id="@id/entry"        android:layout_width="fill_parent"        android:layout_height="wrap_content"        android:layout_toRightOf="@id/label"        android:layout_alignParentTop="true"/></RelativeLayout>

One final look1. @ indicates it is a resource2. What follows the @, indicates the type of resource.3. What follows the /, indicates the name of the resource4. + indicates we are creating this resource

android:id="@+id/my_view"1 2 34

View Attributes: layout_width & layout_height

XML Attributeandroid:layout_width : Specifies the basic width of the view. android:layout_height : Specifies the basic height of the view.

Suggested values• match_parent – Indicates that the view wants to be as big as its parent.• wrap_content – Indicates that the view wants to be just large enough to fit its

own internal content.• Absolute dimension using dp/dip (density independent pixel) units.

Exampleandroid:layout_width = “match_parent”android:layout_height = “wrap_content”android:layout_width = “120dp”

layout_width and layout_height tip

Warning!! When declaring a view in XML, you must at minimum specify layout_width and layout_height. If you fail to do so, you will NOT be notified at compilation time; however, you will receive a runtime error.

View Attribute: VisibilityXML Attributeandroid:visibility : Controls the initial visibility of the view.

Values• visible – Visible on screen; the default value• invisible – Not displayed, but taken into account during layout (space is left for

it).• gone – Completely hidden, as if the view had not been added.

Default Valuevisible

Exampleandroid:visibility = “visible”

Visibility Example<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" >

<Button android:id="@+id/button1" android:layout_width="100dp" android:layout_height="100dp" android:text="Button1" /> <Button android:id="@+id/button2" android:layout_width="100dp" android:layout_height="100dp" android:text="Button2" /> <Button android:id="@+id/button3" android:layout_width="100dp" android:layout_height="100dp" android:text="Button3" /></LinearLayout>

visibility = invisible<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" >

<Button android:id="@+id/button1" android:layout_width="100dp" android:layout_height="100dp" android:text="Button1" /> <Button android:id="@+id/button2" android:layout_width="100dp" android:layout_height="100dp" android:text="Button2" android:visibility="invisible" /> <Button android:id="@+id/button3" android:layout_width="100dp" android:layout_height="100dp" android:text="Button3" /></LinearLayout>

visibility = gone<?xml version="1.0" encoding="utf-8"?><LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="horizontal" >

<Button android:id="@+id/button1" android:layout_width="100dp" android:layout_height="100dp" android:text="Button1" /> <Button android:id="@+id/button2" android:layout_width="100dp" android:layout_height="100dp" android:text="Button2" android:visibility="gone" /> <Button android:id="@+id/button3" android:layout_width="100dp" android:layout_height="100dp" android:text="Button3" /></LinearLayout>

Many more XML Attributes

• The View class itself has several more attributes

• Each specialized view has additional/unique attributes

View attributes in XML and Java

• All attributes in XML can be changed with Java methods.

Accessing Views declared in XML from Java

The easiest way to find a handle to a View in code is to assign the view an ID in XML.

Accessing Views declared in XML from Java

• In code, use the method findViewById(int) to return the view.

Android Resources

• Resources is a broad term in Android.

• A Resource can be1. Image2. String3. Layout4. Integer5. Color6. Drawable (aka Image)

4

Android Resources

• Resources are defined by placing files in the /res directory of your project.

• Resources can be accessed in code and XML.

Android Resources

Key points to remember1. Every resource has an ID

2. Every resource has a specific type

3. Resources have a specific location and file they are defined in.

Types of resources

Directory Resource Type

anim/ XML files that define tween animations.

color/ XML files that define a state list of colors.

drawable/ Bitmap files (.png, .9.png, .jpg, .gif) or XML files that are compiled into drawable resources

layout/ XML files that define a user interface layout.

menu/ XML files that define application menus, such as an Options Menu, Context Menu, or Sub Menu.

values/ XML files that contain simple values, such as strings, integers, and colors.

xml/ Arbitrary XML files that can be read at runtime.

Default and Alternative Resources

For any type of resource, you can specify default and multiple alternative resources for your application.

Default resources • Used regardless of the device configuration or when there

are no alternative resources that match the current configuration.

Alternative resources• Used with a specific configuration. To specify that a group of

resources are for a specific configuration, append an appropriate configuration qualifier to the directory name.

Default and Alternative Resources

• For example, default UI is saved in res/layout/ directory; however, landscape UI is saved in res/layout-land/ directory.

• Extra high density photos (for devices with a lot of pixels) are saved in res/drawable-xhdpi; however drawables for any device go in res/drawable

Resources and the R class

• Once you add a resource in the /res folder, the platform automatically parses it and links the resource ID to the R class.

• The R class maps each resource ID to its location or compiled content.

R class

• The R class is auto-generated for you.

• Do NOT edit this file!!!

• You use this class in your source code as a short-hand way to access your project’s resources.

Android Measurement Units

1. px – Equal to the size of a pixel on the device

2. dp/dip – dots per inch or the quantity of pixels within a physical area of the screen.

3. sp – Scale independent pixels. Very similar to dp, but is also scaled by user’s font size preference.

Best practice for units

• px – never use them because the actual representation can vary across devices.

• dp – recommended practice because allows view dimensions in your layout to resize properly for different screen densities.

• sp – recommended for font size

Many types of devices run Android

The difference density independence can make

Without density independence. Uses px

With density independence. Uses dp