Wednesday, 20 June 2012

Basic Styling (Adding Basic Behavior with jQuery)


The next step is to add some JavaScript to the page to support some basic dynamic behavior. In particular, we will allow users to show and hide the big honking navigation section in the header so that they only see it when they want to. To make this work, we’ll write some new CSS and use some JavaScript to apply the new CSS to the existing HTML.


First, let’s take a look at the new CSS. Step 1 is to hide the ul elements in the header so they don’t show up when the user first loads the page. If you are following along at home, open your android.css file and add the following: #header ul.hide { display: none;
}
This won’t actually hide anything until you add the hide class to the ul elements (you’ll do this shortly with some JavaScript). Next, define the styles for the button that will show and hide the menu. We haven’t created the HTML for the button yet. For your information, it’s going to look like this:
<div class="leftButton" onclick="toggleMenu()">Menu</div>
I’ll describe the button HTML in detail in the section “Adding Basic Behavior with jQuery” on page 28, so don’t add the preceding line of code to your HTML file. The important thing to understand is that it’s a div with the class leftButton and it’s going to be in the header.
Here is the CSS style for the button (you can go ahead and add this to the android.css  file):
#header div.leftButton {
position: absolute;
top: 7px;
left: 6px;
height: 30px;
font-weight: bold;
text-align: center;
color: white;
text-shadow: rgba (0,0,0,0.6) 0px -1px 1px;
line-height: 28px;
border-width: 0 8px 0 8px;
-webkit-border-image: url(images/button.png) 0 8 0 8;


For the graphics used in this chapter, you can download the example files from http://examples.oreilly.com/catalog/9781449383268 and copy
them from the images directory. Put these copies into an images subdirectory beneath the directory that contains your HTML document (you’ll probably need to create the images directory). We’ll be talking
about jQTouch in detail in Chapter 4 Taking it from the top, set the position to absolute to remove the div from the Document flow. This allows you to set its top and left pixel coordinates. Set the height to 30px so it’s big enough to tap easily. Style the text bold, white with a slight drop shadow, and centered in the box.
In CSS, the rgb function is an alternative to the familiar hex notation typically used to specify colors (e.g., #FFFFFF). rgb(255, 255, 255) and rgb(100%, 100%, 100%) are

both the same as #FFFFFF. More recently, the rgba() function has been introduced, which allows you to specify a fourth parameter that defines the alpha value (i.e., opacity) of the color. The range of allowable values is 0 to 1, where 0 is fully transparent  and 1 is fully opaque; decimal values between 0 and 1 will be rendered translucent.
The line-height declaration moves the text down vertically in the box so it’s not flush
against the top border.
The border-width and -webkit-border-image lines require a bit of explanation. These two properties together allow you to assign portions of a single image to the border area of an element. If the box resizes because the text increases or decreases, the border image will stretch to accommodate it. It’s really a great thing because it means fewer images, less work, less bandwidth, and shorter load times.
The border-width line tells the browser to apply a 0 width border to the top, an 8px border to the right, a 0 width border to the bottom, and an 8px width border to the left (i.e., the four parameters start at the top of the box and work their way around clockwise). You don’t need to specify a color or style for the border.
With the border widths in place, you can apply the border image. The five parameters from left to right are: the URL of the image, the top width, the right width, the bottom width, and the left width (again, clockwise from top). The URL can be absolute (http://example.com/myBorderImage.png) or relative. Relative paths are based on the location of the stylesheet, not the HTML page that includes the stylesheet.
When I first encountered the border image property, I found it odd that I had to specify the border widths when I had already done so with the border-width property. After some painful trial and error, I
discovered that the widths in the border-image property are not border widths; they are the widths to slice from the image. Taking the right border as an example, I’m telling the browser to take the left 8px of the image and apply them to the right border, which also happens to have an 8px width It is possible to do something irrational such as applying the right 4 pixels of an image to a border that is 20px wide. To make this work properly, you have to use the optional parameters of webkit-borderimage that instruct the image what to do with the slice in the available border space (repeat, stretch, round, etc.). In three years of trying, I
have failed to come up with any sane reason to do this, so I won’t waste space here describing this confusing and impractical option of an otherwise killer feature. Okay, time for some JavaScript. In preparation for the JavaScript you’re about to write, you need to update your HTML document to include jquery.js and android.js. Add  these lines to the head section of your HTML document:

<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" src="android.js"></script>
jQuery downloads, documentation, and tutorials are available at http: //jquery.com. To use jQuery, you will need to download it from there, rename the file you downloaded (such as jquery-1.3.2.min.js) to
jquery.js, and put a copy of it in the same directory as your HTML document.
The primary duty of the JavaScript in android.js is to allow users to show and hide the nav menus. Copy the following JavaScript into a file called android.js and save it in the same folder as the HTML file: if (window.innerWidth && window.innerWidth <= 480) { $(document).ready(function(){ $('#header ul').addClass('hide');$('#header').append('<div class="leftButton" onclick="toggleMenu()">Menu</div>');
}); function toggleMenu() {
$('#header ul').toggleClass('hide');
$('#header .leftButton').toggleClass('pressed');
}
}
The entire block of code is wrapped in an if statement that checks to make sure the innerWidth property of the window object exists (it doesn’t exist in some versions of Internet Explorer) and that the width is less than or equal to 480px (a reasonable maximum width for the most phones). By adding this line, we ensure that the code executes only when the user is browsing the page with a typical Android phone or
some other similarly sized device. If you are testing your Android web pages using the desktop version
of Chrome as described in “Don’t Have a Website?” on page 13, the if statement here will fail if your browser’s window width is too large. Manually resize your window to be as narrow as possible and
refresh the page.
Here we have the so-called “document ready” function. If you are new to jQuery, this can be a bit intimidating, and I admit that it took me a while to memorize the syntax. However, it’s worth taking the time to commit it to memory, because you’ll be using it a lot. The document ready function basically says, “When the document is ready, run this code.” More on why this is important in a sec.


This is typical jQuery code that begins by selecting the uls in the header and adding the hide CSS class to them. Remember, hide is the selector we used in the CSS above. The net effect of executing this line is to, well, “hide” the header ul elements. Had we not wrapped this line in the document ready function, it
would have most likely executed before the uls were even finished loading. This means the JavaScript would load, and this line would fail because the uls wouldn’t exist yet. Then, the page would continue
loading, the uls would appear, and you’d be scratching your head (or smashing your keyboard), wondering why the JavaScript wasn’t working . Here is where we append a button to the header that will allow the user to show and hide the menu (Figure 2-8). It has a class that corresponds to the CSS we wrote previously for .leftButton, and it has an onclick handler that calls the function toggleMenu() that comes next.

The toggleMenu()function uses jQuery’s toggleClass() function to add or remove the specified class to the selected object. On this line, we toggle the hide class on the header uls.






Sunday, 17 June 2012

Basic Styling ( Adding the Android CSS )


There are a number of UI conventions that make an Android app look like an Android   app. In the next section, we’ll add the distinctive title bar, lists with rounded corners, finger-friendly links that look like glossy buttons, etc. With the text editor of your choice, create a file named android.
css and add the code shown in then save the file in the same directory as your HTML document.body
 {background-color: #ddd; /* Background color */

color: #222; /* Foreground color used for text */
font-family: Helvetica;
font-size: 14px;
margin: 0; /* Amount of negative space around the
outside of the body */
padding: 0; /* Amount of negative space around the
inside of the body */}
All text on Android is rendered using a custom font named Droid. The Droid font family was specifically built for mobile devices, has excellent character set support, and contains three variants: Droid Sans, Droid
Sans Mono, and Droid Serif. Therefore, specifying a font family of Helvetica as we’ve done here will only have an effect on devices other than Android.
Now let’s attack the header div that contains the main home link (i.e., the logo link) and the primary and secondary site navigation. The first step is to format the logo link as a clickable title bar. Add the following to the android.css file:
#header h1 {
margin: 0;
padding: 0;
}
#header h1 a {
background-color: #ccc;
border-bottom: 1px solid #666;
color: #222;
display: block;
font-size: 20px;
font-weight: bold;
padding: 10px 0;
text-align: center;
text-decoration: none;
}
We’ll format the primary and secondary navigation ul blocks identically, so we can just use the generic tag selectors (i.e., #header ul) as opposed to the tag IDs
 (i.e., #header
ul#utility, #header ul#nav):
#header ul {
list-style: none;
margin: 10px;
padding: 0;
}
#header ul li a {
background-color: #FFFFFF;
border: 1px solid #999999;
color: #222222;

display: block;
font-size: 17px;
font-weight: bold;
margin-bottom: -1px;
padding: 12px 10px;
text-decoration: none;
}
Pretty simple so far, right? With this little bit of CSS, we have already made a big
improvement on the Android page design (Figure 2-5). Next, add some padding to the
content and sidebar divs to indent the text from the edge of the screen a bit (Figure 2-6):
#content, #sidebar {
padding: 10px;
}

You might be wondering why we’re adding padding to the content and sidebar elements instead of setting it globally on the body element itself. The reason is that it’s very common to have elements displayed edge to
edge (as with the header in this example). Because of this, padding applied to the body or some other element that’s wrapped around lots of others can become more trouble than it’s worth.

The content in the footer of this page is basically a rehash of the navigation element (the ul element with the ID nav) at the top of the page, so you can remove the footer from the Android version of the page by setting the display to none, as follows:
#footer {
display: none;
}




Friday, 15 June 2012

Prepare a Separate Android Stylesheet


Prepare a Separate Android Stylesheet

I’m as DRY as the next guy, but in the real world you’re better off making a clean break
between your desktop browser stylesheet and your Android stylesheet. Take my word
for it and just make two completely independent files; you’ll sleep better. The alternative
is to wedge all of your CSS rules into a single stylesheet, which is a bad idea for a
number of reasons, the most obvious of which is that you’d be sending a bunch of
irrelevant desktop style rules to the phone, which is a waste of precious bandwidth and
memory.
DRY stands for “don’t repeat yourself,” and is a software development
principle that states, “Every piece of knowledge must have a single, unambiguous,
authoritative representation within a system.” The term
was coined by Andrew Hunt and David Thomas in their book The
Pragmatic Programmer (Addison-Wesley Professional).
To specify a stylesheet specifically for Android, replace the stylesheet link tag in the
sample HTML document with ones that use the following expressions:
<link rel="stylesheet" type="text/css"
href="android.css" media="only screen and (max-width: 480px)" />
<link rel="stylesheet" type="text/css"
href="desktop.css" media="screen and (min-width: 481px)" />


I specifically used max-width and min-width here so that you can resize
your desktop browser and see the mobile version of the page. If you
would prefer to serve the desktop.css stylesheet to desktop users regardless
of their browser window size, use max-device-width and mindevice-
width instead.
The Wireless Universal Resource File (WURFL) contains information
you can use to identify a huge number of wireless devices, including
Android devices. If you need to detect Android devices with a width
greater than 480px (such as a tablet) or if you don’t want the mobile
version of the site to appear when users resize their browser window
below 480px, you can use WURFL’s PHP API to precisely detect specific
browsers. See the Appendix for more information on WURFL.
Here, desktop.css refers to your existing desktop stylesheet, and android.css is a new file
that we’ll be discussing in detail in a bit. The desktop.css file is not essential, but you
can use the stylesheet from the previous chapter if you’d like.
If you’re following along using the sample HTML document shown in
Example 2-1, you’ll need to rename screen.css to desktop.css, but since
we’re focused on the Android stylesheet, you can ignore the desktop
stylesheet completely. If it fails to load, your browser won’t get too
upset.
However, if you’d like to use Chrome to test the Android-optimized
version of the site, you should replace the reference to desktop.css with
a reference to android.css. That way, you’ll get to run the Android version
of your site whether you load it from a phone or the desktop
browser.
Regrettably, Internet Explorer will not understand these expressions, so we have to add
a conditional comment (shown in bold) that links to the desktop version of the CSS:
<link rel="stylesheet" type="text/css"
href="android.css" media="only screen and (max-width: 480px)" />
<link rel="stylesheet" type="text/css"
href="desktop.css" media="screen and (min-width: 481px)" />
<!--[if IE]>
<link rel="stylesheet" type="text/css" href="explorer.css" media="all" />
<![endif]-->
So now it’s time to edit the HTML document (if you haven’t already done that as you
were following along): delete the existing link to the screen.css file, and replace it with
the lines just shown. This way, you will have a clean slate for the Android-specific CSS
in this chapter.

Control the Page Scaling

Unless you tell it otherwise, the Android browser will assume your page is 980px wide
(Figure 2-3). In the majority of cases, this works great. However, you are going to format
the content specifically for the smaller dimensions of the Android phone, so you must
let the mobile browser know about it by adding a viewport meta tag to the head element
of the HTML document:
<meta name="viewport" content="user-scalable=no, width=device-width" />
Desktop browsers will ignore the viewport meta tag, so you can include
it without worrying about the desktop version of your site.


Merely by suppressing the desktop stylesheet and configuring your viewport, you will
have already given your Android users an enhanced experience (Figure 2-4). To really
impress them, let’s start building the android.css stylesheet.


If you don’t set the viewport width, the page will be zoomed out when
it first loads. It’s tough to say exactly what the zoom level will be because
the Android browser includes a setting that allows users to set the default
zoom. The options are Far, Medium (the default), or Close. Even
if you do set the viewport width, these user-defined settings will affect
the zoom level of your app.




BASIC STYLING


BASIC STYLING


Ultimately, we are going to build a native Android app using HTML, CSS, and Java-
Script. The first step on this journey is to get comfortable styling HTML to look like a
mobile app. In this chapter, I’ll show you how to apply CSS styles to a bunch of existing
HTML pages so that they are easily navigable on an Android phone. So, in addition to
moving closer to building a native app, you’ll be learning a practical (and valuable) skill
that you can use immediately.

Don’t Have a Website?

If you’ve been testing all your web pages locally on your personal computer, you won’t
be able to view them on your Android phone without setting up a server. You have a
couple choices:
• Host your web pages on a web server and connect to that server from your Android
phone. Chances are good that your Internet Service Provider (ISP) offers complimentary
web hosting, but this usually only supports basic features such as HTML.
By the time we get to Chapter 6, we’re going to need to use PHP, a scripting language
that runs on the web server, so you should look into an inexpensive hosting
service. Many companies, such as Laughing Squid, offer entry-level hosting with
PHP for under $10 a month.
• Host them on a web server running on your computer and connect to the web
server running on your computer from your Android phone. This only works when
your Android phone and computer are on the same WiFi network.
This chapter is set up so you can try the examples as you go through it. So, no matter
which option you choose for viewing the web pages, try reloading them in a browser
(preferably the Android browser) each time you add something new to one of the samples.
However, be sure to save your file in your text editor before you reload it in the
browser or you won’t see your changes.

RUNING A WEB SERVER LOCALLY 


All current mainstream operating systems (Linux, Windows, Mac OS X) include some
sort of web server. On Mac OS X, open System Preferences, choose Sharing, and enable
Web Sharing. Once you’ve started Web Sharing, the Web Sharing preferences will
display the URL of your personal website (this includes anything you’ve put in the
Sites directory in your home directory). It will be of the form http://local-hostname/
~your-username.
On some versions of Linux, such as Ubuntu, you will need to go through some additional
steps to install and enable a web server. First, install Apache at the command
line with sudo aptitude install apache2. Next, enable the user directory module with
sudo a2enmod userdir. Once that’s done, restart Apache with this command:
sudo /etc/init.d/apache2 restart. After you’ve done that, you can create a directory
called public_html in your home directory and access any files in there with a URL such
as http://local-hostname/~your-username.
On Windows, things are a little more involved. You need to be running a version of
Windows that includes Internet Information Services (IIS) and enable it by going into
the Control Panel and making your way to Turn Windows Features On or Off. After
you’ve done this, put your web documents in your IIS document root, which is typically
located at C:\inetpub\wwwroot. If you’d prefer to run Apache on Windows, check out
a prepackaged solution such as EasyPHP, or check out the Wikipedia page on this topic
at http://en.wikipedia.org/wiki/Comparison_of_WAMPs.

First Steps

Theory is great, but I’m a “show me, don’t tell me” kinda guy so let’s dive in.
Imagine you have a website that you want to “mobile-ize” (Figure 2-1). In this scenario,
there are a number of easy things you can do to optimize a site for Android. I’ll go over
your options in this chapter.
Figure 2-2 shows what this web page looks like on the Android phone. It’s usable, but
far from optimized for Android.
Example 2-1 shows an abbreviated version of the website shown in Figure 2-2. This is
the HTML you’ll be working with in this chapter. You can download it from this book’s
website if you’d like to try styling it as you go through the chapter. The desktop stylesheet
(screen.css) is not shown as it is not essential, but you can use the stylesheet from
the previous chapter if you’d like to have something to play with.


<html>
<head>
<link rel="stylesheet" href="screen.css" type="text/css" />
<title>Jonathan Stark</title>
</head>
<body>
<div id="container">
<div id="header">
<h1><a href="./">Jonathan Stark</a></h1>
<div id="utility">
<ul>
<li><a href="about.html">About</a></li>
<li><a href="blog.html">Blog</a></li>
<li><a href="contact.html">Contact</a></li>
</ul>
</div>
<div id="nav">

<ul>
<li><a href="consulting-clinic.html">Consulting Clinic</a></li>
<li><a href="on-call.html">On Call</a></li>
<li><a href="development.html">Development</a></li>
<li><a href="http://www.oreilly.com">O'Reilly Media, Inc.</a></li>
</ul>
</div>
</div>
<div id="content">
<h2>About</h2>
<p>Jonathan Stark is a web developer, speaker, and author. His
consulting firm, Jonathan Stark Consulting, Inc., has attracted
clients such as Staples, Turner Broadcasting, and the PGA Tour.
...
</p>
</div>
<div id="sidebar">
<img alt="Manga Portrait of Jonathan Stark"
src="jonathanstark-manga-small.png"/>
<p>Jonathan Stark is a mobile and web application developer who the
Wall Street Journal has called an expert on publishing desktop
data to the web.</p>
</div>
<div id="footer">
<ul>
<li><a href="services.html">Services</a></li>
<li><a href="about.html">About</a></li>
<li><a href="blog.html">Blog</a></li>
</ul>
<p class="subtle">Jonathan Stark Consulting, Inc.</p>
</div>
</div>
</body>
</html>

For years, web developers used tables to lay out elements in a grid. Advances
in CSS and HTML have rendered that approach not only obsolete,
but undesirable. Today, we primarily use the div element (along
with a variety of attributes) to accomplish the same thing, but with more
control. Although a complete explanation of div-based layouts is well
outside the scope of this book, you’ll see plenty of examples of it as you
read through the book. To learn more, please check out Designing with
Web Standards by Jeffrey Zeldman (New Rider Press), which covers the
issue in greater detail.




CHAPTER 1


Applying a stylesheet
So now you understand the basics of CSS, but how do you apply a stylesheet to an
HTML page? Quite simple, actually! First, you save the CSS somewhere on your server
(usually in the same directory as your HTML file, though you can put it in a subdirectory).
Next, link to the stylesheet in the head of the HTML document, as shown in
Example 1-6. The href attribute in this example is a relative path, meaning it points to
a text file named screen.css in the same directory as the HTML page. You can also
specify absolute links, such as the following:
http://example.com/screen.css
If you are saving your HTML files on your local machine, you’ll want
to keep things simple: put the CSS file in the same directory as the HTML
file and use a relative path as shown in Example 1-6.
Example 1-6. Linking to a CSS stylesheet
<html>
<head>
<title>My Awesome Page</title>
<link rel="stylesheet" href="screen.css" type="text/css" />
</head>
<body>
<h1 class="loud">Hi there!</h1>
<p>Thanks for visiting my web page.</p>
<p>I hope you like it.</p>
<ul>
<li class="loud">Pizza</li>
<li>Beer</li>
<li>Dogs</li>
</ul>
</body>
</html>
Example 1-7 shows the contents of screen.css. You should save this file in the same
location as the HTML file:
Example 1-7. A simple stylesheet
body {
font-size: 12px;
font-weight: bold;
font-family: Arial;
}
a { font-style: italic; }
h1 a { font-style: italic; }
.loud { font-style: italic; }
#highlight { background-color: yellow; }

It’s worth pointing out that you can link to stylesheets that are hosted
on domains other than the one hosting the HTML document. However,
it’s considered very rude to link to someone else’s stylesheets without
permission, so please only link to your own.
For a quick and thorough crash course in CSS, I highly recommend CSS Pocket Refer
ence: Visual Presentation for the Web by Eric Meyer (O’Reilly). Meyer is the last word
when it comes to CSS, and this particular book is short enough to read during the typical
morning carpool (unless you are the person driving, in which case it could take considerably
longer—did I say “crash” course?).
Introduction to JavaScript
At this point you know how to structure a document with HTML and how to modify
its visual presentation with CSS. Now we’ll add some JavaScript to make it do stuff.
JavaScript is a scripting language that you can add to an HTML page to make it more
interactive and convenient for the user. For example, you can write some JavaScript
that will inspect the values typed in a form to make sure they are valid. Or, you can
have JavaScript show or hide elements of a page depending on where the user clicks.
JavaScript can even contact the web server to execute database changes without refreshing
the current web page.
Like any modern scripting language, JavaScript has variables, arrays, objects, and all
the typical control structures (e.g., if, while, for). Example 1-8 shows a snippet of
JavaScript that illustrates several core concepts of the language.
Example 1-8. Basic JavaScript syntax
var foods = ['Apples', 'Bananas', 'Oranges'];
for (var i=0; i<foods.length; i++) {
if (foods[i] == 'Apples') {
alert(foods[i] + ' are my favorite!');
} else {
alert(foods[i] + ' are okay.');
}
}
Here’s an explanation of what’s happening here:
Define an array (a list of values) named foods that contains three elements.
Open a typical for loop that initializes a variable named i to 0 and specifies an exit
criteria—in this case, exit when i is greater than the length of the foods array, and
increment i by 1 each time through the loop (i++ is shorthand for “add 1 to the
current value of i”).
A garden variety if that checks to see if the current element of the array is equal to
Apples.

Displayed if the current element of the array is equal to Apples.
Displayed if the current element of the array is not equal to Apples.
Here are some points about JavaScript’s syntax that are worth noting:
• Statements are terminated with semicolons (;)
• Code blocks are enclosed in curly braces ({})
• Variables are declared using the var keyword
• Array elements can be accessed with square bracket notation ([])
• Array keys are assigned beginning at 0
• The single equals sign (=) is the assignment operator (assigns a value to a variable)
• The double equals sign (==) is the equivalence logical operator (compares two values
and evaluates to true if they are equivalent)
• The plus sign (+) is the string concatenation operator (combines two strings
together)
For our purposes, the most important feature of JavaScript is that it can interact with
the elements of an HTML page (the cool kids call this “manipulating the DOM”).
Example 1-9 shows a simple bit of JavaScript that changes some text on the page when
the user clicks on the h1.
DOM stands for Document Object Model and in this context it represents
the browser’s understanding of an HTML page. You can read more
about the DOM here: http://en.wikipedia.org/wiki/Document_Object
_Model.
Example 1-9. Simple onclick handler
<html>
<head>
<title>My Awesome Page</title>
<script type="text/javascript" charset="utf-8">
function sayHello() {
document.getElementById('foo').innerHTML = 'Hi there!';
}
</script>
</head>
<body>
<h1 id="foo" onclick ="sayHello()">Click me!</h1>
</body>
</html>

Here’s an explanation:
A script block at the head of the HTML document.
This line defines a single JavaScript function named sayHello() inside the script
block.
The sayHello() function contains a single statement that tells the browser to look
through the document for an element that has the ID foo, and set its inner HTML
contents to Hi there! The effect of this in the browser is that the text “Click me!”
will be replaced with “Hi there!” when the user clicks the h1 element.
End of the sayHello() function.
End of the script block.
The onclick attribute of the h1 element tells the browser to do something when the
user clicks the h1 element, namely, to run the sayHello() function.
Back in the bad old days of web development, different browsers had different support
for JavaScript. This meant that your code might run in Safari 2 but not in Internet
Explorer 6. You had to take great pains to test each browser (and even different versions
of the same browser) to make sure your code would work for everyone. As the number
of browsers and browser versions grew, it became impossible to test and maintain your
JavaScript code for every environment. At that time, web programming with JavaScript
was hell.
Enter jQuery. jQuery is a relatively small JavaScript library that allows you to write
your JavaScript code in a way that will work the same in a wide variety of browsers.
What’s more, it greatly simplifies a number of common web development tasks. For
these reasons, I use jQuery in most of my web development work, and I’ll be using it
for the JavaScript examples in this book. Example 1-10 is a jQuery rewrite of Example
1-9.
Example 1-10. jQuery onclick handler
<html>
<head>
<title>My Awesome Page</title>
<script type="text/javascript" src="jquery.js"></script>
<script type="text/javascript" charset="utf-8">
function sayHello() {
$('#foo').text('Hi there!');
}
</script>
</head>
<body>
<h1 id="foo" onclick="sayHello()">Click me!</h1>
</body>
</html>

This line includes the jquery.js library. It uses a relative path, meaning the file exists
in the same directory as the page that is using it (this example won’t function correctly
unless the jQuery library, jquery.js, is there). However, you can include it
directly from a variety of places where it’s available.
Notice the reduction in the amount of code we need to write to replace the text in
the h1 element. This might not seem like a big deal in such a trivial example, but I
can assure you that it’s a lifesaver in complex solutions.
We’ll be seeing plenty of real-world jQuery examples later on, so I’m going to leave it
at that for the moment.
jQuery downloads, documentation, and tutorials are available at http:
//jquery.com. To use jQuery as shown in Example 1-9, you will need to
download it from there, rename the file you downloaded (such as
jquery-1.4.2.min.js) to jquery.js, and put a copy of it in the same directory
as your HTML document.




CHAPTER 1


The body and head are always wrapped in an html element. Example 1-3 shows the
snippet in the context of a proper HTML document. For now the head section contains
a title element, which tells the browser what text to display in the title bar of the
window.
Example 1-3. A proper HTML document
<html>
<head>
<title>My Awesome Page</title>
</head>
<body>
<h1>Hi there!</h1>
<p>Thanks for visiting my web page.</p>
<p>I hope you like it.</p>
<ul>
<li>Pizza</li>
<li>Beer</li>
<li>Dogs</li>
</ul>
</body>
</html>
Normally, when you are using your web browser you are viewing pages that are hosted
on the Internet. However, browsers are perfectly good at displaying HTML documents
that are on your local machine as well. To show you what I mean, I invite you to crack
open a text editor and enter the code in Example 1-3.
Picking the Right Text Editor
Some text editors are not suited for authoring HTML. In particular, you want to avoid
editors that support rich text editing, like Microsoft WordPad (Windows) or TextEdit
(Mac OS X). These types of editors can save their files in formats other than plain text,
which will break your HTML. If you must use TextEdit, save in plain text by choosing
Format→Make Plain Text. In Windows, use Notepad instead of WordPad.
If you are in the market for a good text editor, my recommendation on the Mac is
TextMate. There is a clone version for Windows called E Text Editor.
If free is your thing, you can download Text Wrangler for Mac. For Windows, Note
pad2 and Notepad++ are highly regarded. Linux comes with an assortment of text
editors, such as vi, nano, emacs, and gedit.
When you are finished entering the code from Example 1-3, save it to your desktop as
test.html and then open it with Chrome by either dragging the file onto the Chrome
application icon or opening Chrome and selecting File→Open File. Double-clicking
test.html will work as well, but it could open in your text editor or another browser,
depending on your settings.

Even if you aren’t running Mac OS X, you should use Chrome when
testing your Android web apps on a desktop web browser, because
Chrome is the closest desktop browser to Android’s mobile browser.
Chrome is available for Mac and Windows from http://google.com/
chrome.
Introduction to CSS
As you’ve seen, browsers render certain HTML elements with distinct styles (for example,
headings are large and bold, paragraphs are followed by a blank line, and so
forth). These styles are very basic and are primarily intended to help the reader understand
the structure and meaning of the document.
To go beyond this simple structure-based rendering, you use Cascading Style Sheets
(CSS). CSS is a stylesheet language that you use to define the visual presentation of an
HTML document. You can use CSS to define simple things like the text color, size, and
style (bold, italic, etc.), or complex things like page layout, gradients, opacity, and much
more.
Example 1-4 shows a CSS rule that instructs the browser to display any text in the body
element using the color red. In this example, body is the selector (this specifies what is
affected by the rule) and the curly braces enclose the declaration (the rule itself). The
declaration includes a set of properties and their values. In this example, color is the
property, and red is the value of the color property.
Example 1-4. A simple CSS rule
body { color: red; }
Property names are predefined in the CSS specification, which means that you can’t
just make them up. Each property expects an appropriate value, and there can be lots
of appropriate values and value formats for a given property.
For example, you can specify colors with predefined keywords like red, or by using
HTML color code notation, which uses a hexadecimal notation: a hash/pound sign
(#) followed by three pairs of hexadecimal digits (0–F) representing (from left to right)
red, green, and blue values (red is represented as #FF0000). Properties that expect measurements
can accept values like 10px, 75%, and 1em. Example 1-5 shows some common
declarations. The color code shown for background-color corresponds to the CSS
“gray.”
Example 1-5. Some common CSS declarations
body {
color: red;
background-color: #808080;
font-size: 12px;
font-style: italic;
font-weight: bold;

font-family: Arial;
}
Selectors come in a variety of flavors. If you want all of your hyperlinks (the a element)
to display in italics, add the following to your stylesheet:
a { font-style: italic; }
If you want to be more specific and only italicize the hyperlinks that are contained
somewhere within an h1 tag, add the following to your stylesheet:
h1 a { font-style: italic; }
You can also define your own custom selectors by adding id and/or class attributes to
your HTML tags. Consider the following HTML snippet:
<h1 class="loud">Hi there!</h1>
<p>Thanks for visiting my web page.</p>
<p>I hope you like it.</p>
<ul>
<li class="loud">Pizza</li>
<li>Beer</li>
<li>Dogs</li>
</ul>
If we add .loud { font-style: italic; } to the CSS for this HTML, Hi there! and
Pizza will show up italicized because they both have the loud class. The dot in front of
the .loud selector is important—it’s how the CSS knows to look for HTML tags with
a class of loud. If you omit the dot, the CSS will look for a loud tag, which doesn’t exist
in this snippet (or in HTML at all, for that matter).
Applying CSS by id is similar. To add a yellow background fill to the highlight paragraph
tag, use the following rule:
#highlight { background-color: yellow; }
Here, the # symbol tells the CSS to look for an HTML tag with the ID highlight.
To recap, you can opt to select elements by tag name (e.g., body, h1, p), by class name
(e.g., .loud, .subtle, .error), or by ID (e.g., #highlight, #login, #promo). And, you can
get more specific by chaining selectors together (e.g., h1 a, body ul .loud).
There are differences between class and id. Use class attributes when
you have more than one item on the page with the same class value.
Conversely, id values have to be unique to a page.
When I first learned this, I figured I’d just always use class attributes so
I wouldn’t have to worry about whether I was duping an ID value.
However, selecting elements by ID is much faster than by class, so you
can hurt your performance by overusing class selectors.


CHAPTER 1


Example 1-2. Unordered list
<ul>
<li>Pizza</li>
<li>Beer</li>
<li>Dogs</li>
</ul>
The tags covered so far are all block tags. The defining characteristic of block tags is
that they are displayed on a line of their own, with no elements to the left or right of
them. That is why the heading, paragraphs, and list items progress down the page
instead of across it. The opposite of a block tag is an inline tag, which, as the name
implies, can appear in a line. The emphasis tag (em) is an example of an inline tag, and
it looks like this:
<p>I <em>really</em> hope you like it.</p>
The granddaddy of the inline tags—and arguably the coolest feature of HTML—is the
a tag. The “a” stands for anchor, but at times I’ll also refer to it as a link or hyperlink.
Text wrapped in an anchor tag is clickable, such that clicking on it causes the browser
to load a new HTML page.
To tell the browser which new page to load, we have to add what’s called an attribute
to the tag. Attributes are named values that you insert into an open tag. In an anchor
tag, you use the href attribute to specify the location of the target page. Here’s a link
to Google’s home page:
<a href="http://www.google.com/">Google</a>
That might look like a bit of a jumble if you are not used to reading HTML, but you
should be able to pick out the URL for the Google home page. You’ll be seeing a lot of
a tags and href attributes throughout the book, so take a minute to get your head around
this if it doesn’t make sense at first glance.
There are a couple of things to keep in mind regarding attributes. Different
HTML tags allow different attributes. You can add multiple
attributes to an open tag by separating them with spaces. You never add
attributes to a closing tag. There are hundreds of possible combinations
of attributes and tags, but don’t sweat it—we only have to worry about
a dozen or so in this entire book.
The HTML snippet that we’ve been looking at would normally reside in the body section
of a complete HTML document. An HTML document is made up of two sections: the
head and the body. The body is where you put all the content that you want users to
see. The head contains information about the page, most of which is invisible to the
user.

Chapter 1


Pros and Cons
Different applications have different requirements. Some apps are a better fit with web
technologies than others. Knowing the pros and cons of each approach will help you
make a better decision about which path is appropriate for your situation.
Here are the pros of native app development:
• Millions of registered credit card owners are one click away
• You can access all the cool hardware features of the device
Here are the cons of native app development:
• You have to pay to become an Android developer
• Your app will run only on Android phones
• You have to develop using Java
• The development cycle is slow (develop, compile, deploy, repeat)
Here are the pros of web app development:
• Web developers can use their current authoring tools
• You can use your current web design and development skills
• Your app will run on any device that has a web browser
• You can fix bugs in real time
• The development cycle is fast
Here are the cons of web app development:
• You cannot access the all cool hardware features of the phone
• You have to roll your own payment system if you want to charge for the app
• It can be difficult to achieve sophisticated UI effects
Which Approach Is Right for You?
Here’s where it gets exciting. The always-online nature of the Android phone creates
an environment in which the lines between a web app and a native app get blurry. There
are even some little-known features of the Android web browser (see Chapter 6) that
allow you to take a web app offline if you want. What’s more, several third-party
projects—of which PhoneGap is the most notable—are actively developing solutions
that allow web developers to take a web app and package it as a native app for Android
and other mobile platforms.
For me, this is the perfect blend. I can write in my native language, release a product
as a pure web app (for Android and any other devices that have a modern browser),
and use the same code base to create an enhanced native version that can access the
device hardware and potentially be sold in the Android Market. This is a great way to

create a “fremium” model for your app—allow free access to the web app and charge
for the more feature-rich native version.
Web Programming Crash Course
The three main technologies we will use to build web apps are HTML, CSS, and Java-
Script. We’ll quickly cover each to make sure we’re all on the same page before plowing
into the fancy stuff.
Introduction to HTML
When you are browsing the web, the pages you are viewing are just text documents
sitting on someone else’s computer. The text in a typical web page is wrapped in HTML
tags, which tell your browser about the structure of the document. With this information,
the browser can decide how to display the information in a way that makes sense.
Consider the web page snippet shown in Example 1-1. On the first line, the string Hi
there! is wrapped in a pair of h1 tags. Notice that the open tag and the close tag are
slightly different: the close tag has a slash (/) as the second character, while the open
tag does not have a slash.
Wrapping text in h1 tags tells the browser that the words enclosed are a heading, which
will cause it to be displayed in large bold text on its own line. There are also h2, h3, h4,
h5, and h6 heading tags. The lower the number, the more important the header, so text
wrapped in an h6 tag will be smaller (i.e., less important-looking) than text wrapped in
an h3 tag.
After the h1 tag in Example 1-1, there are two lines wrapped in p tags. These are called
paragraph tags. Browsers will display each paragraph on its own line. If the paragraph
is long enough to exceed the width of the browser window, the text will bump down
and continue on the next line. In either case, a blank line will be inserted after the
paragraph to separate it from the next item on the page.
Example 1-1. HTML snippet
<h1>Hi there!</h1>
<p>Thanks for visiting my web page.</p>
<p>I hope you like it.</p>
You can also put HTML tags inside other HTML tags. Example 1-2 shows an unordered
list (ul) tag that contains three list items (li). In a browser, this appears as a bulleted
list with each item on its own line. When you have a tag or tags inside another tag, the
inner tags are called child elements, or children, of the parent tag. So in this example,
the li tags are children of the ul parent.

CHAPTER 1



Getting Started
Before we dive in, I’d like to quickly establish the playing field. In this chapter, I’ll define
key terms, compare the pros and cons of the two most common development approaches,
and give a crash course on the three core web technologies used in this book.
Web Apps Versus Native Apps
First, I’d like to define what I mean by web app and native app and consider their pros
and cons.
What Is a Web App?
To me, a web app is basically a website that is specifically optimized for use on a
smartphone. The site content can be anything from a standard small business brochure
site to a mortgage calculator to a daily calorie tracker—the content is irrelevant. The
defining characteristics of a web app are that the user interface (UI) is built with web
standard technologies, it is available at a URL (public, private, or perhaps behind a
login), and it is optimized for the characteristics of a mobile device. A web app is not
installed on the phone, it is not available in the Android Market, and it is not written
with Java.
What Is a Native App?
In contrast, native apps are installed on the Android phone, they have access to the
hardware (speakers, accelerometer, camera, etc.), and they are written with Java. The
defining characteristic of a native app, however, is that it’s available in the Android
Market—a feature that has captured the imagination of a horde of software entrepreneurs
worldwide, me included.