Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Appcelerator Titanium Smartphone App Development Cookbook Second Edition
Appcelerator Titanium Smartphone App Development Cookbook Second Edition

Appcelerator Titanium Smartphone App Development Cookbook Second Edition: Over 100 recipes to help you develop cross-platform, native applications in JavaScript

Arrow left icon
Profile Icon Jason Kneen
Arrow right icon
₱2500.99
Full star icon Full star icon Full star icon Full star icon Full star icon 5 (4 Ratings)
Paperback Nov 2015 368 pages 1st Edition
eBook
₱579.99 ₱2000.99
Paperback
₱2500.99
Subscription
Free Trial
Arrow left icon
Profile Icon Jason Kneen
Arrow right icon
₱2500.99
Full star icon Full star icon Full star icon Full star icon Full star icon 5 (4 Ratings)
Paperback Nov 2015 368 pages 1st Edition
eBook
₱579.99 ₱2000.99
Paperback
₱2500.99
Subscription
Free Trial
eBook
₱579.99 ₱2000.99
Paperback
₱2500.99
Subscription
Free Trial

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Table of content icon View table of contents Preview book icon Preview Book

Appcelerator Titanium Smartphone App Development Cookbook Second Edition

Chapter 1. Building Apps Using Native UI Components

In this chapter, we'll cover the following recipes:

  • Building with windows and views
  • Adding a tabgroup to your app
  • Creating and formatting labels
  • Creating textfields for user input
  • Working with keyboards and keyboard toolbars
  • Enhancing your app with sliders and switches
  • Passing custom variables between windows
  • Creating buttons and capturing click events
  • Informing your users with dialogs and alerts
  • Creating charts using Raphael JS
  • Building an actionbar in Android

Introduction

The ability to create user-friendly layouts with rich, intuitive controls is an important factor in successful app designs. With mobile apps and their minimal screen real estate, this becomes even more important. Titanium leverages a huge amount quantity of native controls found in both the iOS and Android platforms, allowing a developer to create apps just as rich in functionality as those created by native language developers.

How does this compare to the mobile Web? When it comes to HTML/CSS-only mobile apps, savvy users can definitely tell the difference between them and a platform such as Titanium, which allows you to use platform-specific conventions and access your iOS or Android device's latest and greatest features. An application written in Titanium feels and operates like a native app, because all the UI components are essentially native. This means crisp, responsive UI components utilizing the full capabilities and power of your device.

Most other books at this point would start off by explaining the fundamental principles of Titanium and, maybe, give you a rundown of the architecture and expand on the required syntax.

Yawn...!

We're not going to do that, but if you want to find out more about the differences between Titanium and PhoneGap, check out http://www.appcelerator.com/blog/2012/05/comparing-titanium-and-phonegap/.

Instead, we'll be jumping straight into the fun stuff: building our user interface and making a real-world app! In this chapter, you'll learn all of this:

  • How to build an app using windows and views, and understanding the differences between the two
  • Putting together a UI using all the common components, including TextFields, labels, and switches
  • Just how similar the Titanium components' properties are to CSS when it comes to formatting your UI

You can pick and choose techniques, concepts, and code from any recipe in this chapter to add to your own applications or, if you prefer, you can follow each recipe from beginning to end to put together a real-world app that calculates loan repayments, which we'll call LoanCalc from here on.

The complete source code for this chapter can be found in the /Chapter 1/LoanCalc folder.

Building with windows and views

We're going to start off with the very basic building blocks of all Titanium applications: windows and views. By the end of this recipe, you'll have understood how to implement a window and add views to it, as well as the fundamental differences between the two, which are not as obvious as they may seem at first glance.

If you are intending to follow the entire chapter and build the LoanCalc app, then pay careful attention to the first few steps of this chapter, as you'll need to perform these steps again for every subsequent app in the book.

Note

Note

We are assuming that you have already downloaded and installed Appcelerator Studio, along with XCode and iOS SDK or Google's Android SDK, or both.

Getting ready

To follow along with this recipe, you'll need Titanium installed plus the appropriate SDKs. All the examples generally work on either platform unless specified explicitly at the start of a particular recipe.

The quickest way to get started is by using Appcelerator Studio, a full-fledged Integrated Development Environment (IDE) that you can download from the Appcelerator website.

If you prefer, you can use your favorite IDE, such as TextMate, Sublime Text, Dashcode, Eclipse, and so on. Combined with the Titanium CLI, you can build, test, deploy, and distribute apps from the command line or terminal. However, for the purposes of this book, we're assuming that you'll be using Appcelerator Studio, which you can download from https://my.appcelerator.com/auth/signup/offer/community.

To prepare for this recipe, open Appcelerator Studio and log in if you have not already done so. If you need to register a new account, you can do so for free from within the application. Once you are logged in, navigate to File | New | Mobile App Project and select the Classic category on the left (we'll come back to Alloy later on), then select Default Project and click on Next. The details window for creating a new project will appear. Enter LoanCalc, the name of the app, and fill in the rest of the details with your own information, as shown in the following screenshot. We can also uncheck the iPad and Mobile Web options, as we'll be building our application for the iPhone and Android platforms only:

Getting ready

Note

Pay attention to the app identifier, which is written normally in backwards domain notation (for example, com.packtpub.loancalc). This identifier cannot be changed easily after the project has been created, and you'll need to match it exactly when creating provisioning profiles to distribute your apps later on. Don't panic, however: you can change it.

How to do it...

First, open the Resources/app.js file in your Appcelerator Studio. If this is a new project, the studio creates a sample app by default, containing a couple of Windows inside of a TabGroup; certainly useful, but we'll cover tabgroups in a later recipe, so we go ahead and remove all of the generated code. Now, let's create a Window object, to which we'll add a view object. This view object will hold all our controls, such as textfields and labels.

In addition to creating our base window and view, we'll also create an imageview component to display our app logo before adding it to our view (you can get the images we have used from the source code for this chapter; be sure to place them in the Resources folder).

Finally, we'll call the open() method on the window to launch it:

//create a window that will fill the screen
var win1 = Ti.UI.createWindow({
  backgroundColor: '#BBB'  
});

//create the view, this will hold all of our UI controls 
//note the height of this view is the height of the window //minus 20 points for the status bar and padding
var view = Ti.UI.createView({
  top: 20,
bottom: 10,
  left: 10,
  right: 10,
  backgroundColor: '#fff',
  borderRadius: 2
});


//now let's add our logo to an imageview and add that to our //view object. By default it'll be centered.
var logo = Ti.UI.createImageView({
  image: 'logo.png',
  width: 253,
  height: 96,
  top: 10
});
view.add(logo);

//add the view to our window
win1.add(view);

//finally, open the window to launch the app
win1.open();

How to do it...

How it works…

Firstly, it's important to explain the differences between windows and views, as there are a few fundamental differences that may influence your decision on using one compared to the other. Unlike views, windows have some additional abilities, including the open() and close() methods.

If you are coming from a desktop development background, you can imagine a Window as the equivalent of a form or screen; if you prefer web analogies, then a window is more like a page, whereas views are more like a Div.

In addition to these methods, windows have display properties such as full screen and modal; these are not available in views. You'll also notice that while creating a new object, the create keyword is used, such as Ti.UI.createView() to create a view object. This naming convention is used consistently throughout the Titanium API, and almost all components are instantiated in this way.

Windows and views can be thought of as the building blocks of your Titanium application. All your UI components are added to either a window, or a view (which is the child of a Window). There are a number of formatting options available for both of these objects, the properties and syntax of which will be very familiar to anyone who has used CSS in the past. Note that these aren't exactly like CSS, so the naming conventions will be different. Font, Color, BorderWidth, BorderRadius, Width, Height, Top, and Left are all properties that function in exactly the same way as you would expect them to in CSS, and apply to windows and almost all views.

Note

It's important to note that your app requires at least one window to function and that window must be called from within your entry point (the app.js file).

You may have also noticed that we have sometimes instantiated objects or called methods using Ti.UI.createXXX, and at other times, we have used Ti.UI.createXXX. Ti. This is simply a shorthand namespace designed to save time during coding, and it will execute your code in exactly the same manner as the full Titanium namespace does.

Adding a tabgroup to your app

Tabgroups are one of the most commonly used UI elements and form the basis of the layout for many iOS and Android apps in the market today. A tabgroup consists of a sectioned set of tabs, each containing an individual window, which in turn contains a navigation bar and title. On iOS devices, these tabs appear in a horizontal list at the bottom of screen, whereas they appear as upside-down tabs at the top of the screen on Android devices by default, as shown in the following image:

Adding a tabgroup to your app

How to do it...

We are going to create two separate windows. One of these will be defined inline, and the other will be loaded from an external CommonJS JavaScript module.

Before you write any code, create a new JavaScript file called window2.js and save it in your Resources directory, the same folder in which your app.js file currently resides.

Now open the window2.js file you just created and add the following code:

//create an instance of a window
module.exports = (function(){
var win = Ti.UI.createWindow({
  backgroundColor: '#BBB',
  title: 'Settings'
});

return win;
})();

If you have been following along with the LoanCalc app so far, then delete the current code in the app.js file that you created and replace it with the following source. Note that you can refer to the Titanium SDK as Titanium or Ti; in this book, I'll be using Ti:

//create tab group
var tabGroup = Ti.UI.createTabGroup();

//create the window
var win1 = Ti.UI.createWindow({
  backgroundColor: '#BBB',
  title: 'Loan Calculator'
});

//create the view, this will hold all of our UI controls 
var view = Ti.UI.createView({
top: 10,
  bottom: 10,
  left: 10,
  right: 10,
  backgroundColor: '#fff',
  borderRadius: 2,
  layout: 'vertical'
});

//now let's add our logo to an imageview and add that to our //view object
var logo = Ti.UI.createImageView({
  image: 'logo.png',
  width: 253,
  height: 96,
  top: 10
});

view.add(logo);

//add the view to our window
win1.add(view);

//add the first tab and attach our window object (win1) to it
var tab1 = Ti.UI.createTab({  
    icon:'calculator.png',
    title:'Calculate',
  
    window: win1
});

//create the second window for settings tab
var win2 = require("window2");


//add the second tab and attach our external window object //(win2 / window2) to it
var tab2 = Ti.UI.createTab({  
    icon:'settings.png',
    title:'Settings',
    window: win2
});


//now add the tabs to our tabGroup object
tabGroup.addTab(tab1);  
tabGroup.addTab(tab2);  

//finally, open the tabgroup to launch the app
tabGroup.open();

How it works...

Logically, it's important to realize that the tabgroup, when used, is the root of the application and it cannot be included via any other UI component. Each tab within the tabgroup is essentially a wrapper for a single window.

Windows should be created and assigned to the window property. At the time of writing this book, it may be possible to still use the url property (depending on the SDK you are using), but do not use it as it will be removed in later SDKs. Instead, we'll be creating windows using a CommonJS pattern, which is considered the proper way of developing modular applications.

The tabs icon is loaded from an image file, generally a PNG file. It's important to note that in both Android and the iPhone, all icons will be rendered in grayscale with alpha transparency—any color information will be discarded when you run the application.

You'll also notice in the Resources folder of the project that we have two files for each image—for example, one named settings.png and one named settings@2x.png. These represent normal and high-resolution retina images, which some iOS devices support. It's important to note that while specifying image filenames, we never use the @2x part of the name; iOS will take care of using the relevant image, if it's available. We also specify all positional and size properties (width, height, top, bottom, and so on) in non-retina dimensions.

This is also similar to how we interact with images in Android: we always use the normal filename, so it is settings.png, despite the fact there may be different versions of the file available for different device densities on Android.

Finally, notice that we're in the view and we're using vertical as a layout. This means that elements will be laid out down the screen one after another. This is useful in avoiding having to specify the top values for all elements, and, if you need to change one position, having to change all the elements. With a vertical layout, as you modify one element's top or height value, all others shift with it.

There's more...

Apple can be particularly picky when it comes to using icons in your apps; wherever a standard icon has been defined by Apple (such as the gears icon for settings), you should use the same.

A great set of 200 free tab bar icons is available at http://glyphish.com/.

Creating and formatting labels

Whether they are for presenting text content on the screen, identifying an input field, or displaying data within a tablerow, labels are one of the cornerstone UI elements that you'll find yourself using all the time with Titanium. Through them, you'll display the majority of your information to the user, so it's important to know how to create and format them properly.

In this recipe, we'll create three different labels, one for each of the input components that we'll be adding to our app later on. Using these examples, we'll explain how to position your label, give it a text value, and format it.

How to do it...

Open up your app.js file, and put these two variables at the top of your code file, directly under the tabgroup creation declaration. These are going to be the default values for our interest rate and loan length for the app:

//application variables
var numberMonths = 36; //loan length
var interestRate = 6.0; //interest rate

Let's create labels to identify the input fields that we'll be implementing later on. Type the following source code into your app.js file. If you are following along with the LoanCalc sample app, this code should go after your imageview logo, added to the view from the previous recipe:

var amountRow = Ti.UI.createView({
  top: 10,
  left: 0,
  width: Ti.UI.FILL,
  height: Ti.UI.SIZE
});

//create a label to identify the textfield to the user
var labelAmount = Ti.UI.createLabel({
  width : Ti.UI.SIZE,
  height : 30,
  top : 0,
  left : 20,
  font : {
    fontSize : 14,
    fontFamily : 'Helvetica',
    fontWeight : 'bold'
  },
  text : 'Loan amount:   $'
});

amountRow.add(labelAmount);

view.add(amountRow);

var interestRateRow = Ti.UI.createView({
  top: 10,
  left: 0,
  width: Ti.UI.SIZE,
  height: Ti.UI.SIZE
});

//create a label to identify the textfield to the user
var labelInterestRate = Ti.UI.createLabel({
  width : Ti.UI.SIZE,
  height : 30,
  top : 0,
  left : 20,
  font : {
    fontSize : 14,
    fontFamily : 'Helvetica',
    fontWeight : 'bold'
  },
  text : 'Interest Rate:  %'
});

interestRateRow.add(labelInterestRate);

view.add(interestRateRow);

var loanLengthRow = Ti.UI.createView({
  top: 10,
  left: 0,
  width: Ti.UI.FILL,
  height: Ti.UI.SIZE
});

//create a label to identify the textfield to the user
var labelLoanLength = Ti.UI.createLabel({
  width : 100,
  height : Ti.UI.SIZE,
  top : 0,
  left : 20,
  font : {
    fontSize : 14,
    fontFamily : 'Helvetica',
    fontWeight : 'bold'
  },
  text : 'Loan length (' + numberMonths + ' months):'
});

loanLengthRow.add(labelLoanLength);

view.add(loanLengthRow);

How it works...

By now, you should notice a trend in the way in which Titanium instantiates objects and adds them to views/windows, as well as a trend in the way formatting is applied to most basic UI elements using the JavaScript object properties. Margins and padding are added using the absolute positioning values of top, left, bottom, and right, while font styling is done with the standard font properties, which are fontSize, fontFamily, and fontWeight in the case of our example code.

Here are a couple of important points to note:

  • The width property of our first two labels is set to Ti.UI.SIZE, which means that Titanium will automatically calculate the width of the Label depending on the content inside (a string value in this case). This Ti.UI.SIZE property can be used for both the width and height of many other UI elements as well, as you can see in the third label that we created, which has a dynamic height for matching the label's text. When no height or width property is specified, the UI component will expand to fit the exact dimensions of the parent view or window that encloses it.
  • You'll notice that we're creating views that contain a label each. There's a good reason for this. To avoid using absolute positioning, we're using a vertical layout on the main view, and to ensure that our text fields appear next to our labels, we're creating a row as a view, which is then spaced vertically. Inside the row, we add the label, and in the next recipes, we will have all the text fields next to the labels.
  • The textAlign property of the labels works the same way as you'd expect it to in HTML. However, you'll notice the alignment of the text only if the width of your label isn't set to Ti.UI.SIZE, unless that label happens to spread over multiple lines.
    How it works...

Creating textfields for user input

TextFields in Titanium are single-line textboxes used to capture user input via the keyboard, and usually form the most common UI element for user input in any application, along with labels and buttons. In this section, we'll show you how to create a Textfield, add it to your application's View, and use it to capture user input. We'll style our textfield component using a constant value for the first time.

How to do it...

Type the following code after the view has been created but before adding that view to your window. If you've been following along from the previous recipe, this code should be entered after your labels have been created:

//creating the textfield for our loan amount input
var tfAmount = Ti.UI.createTextField({
  width: 140,
  height: 30,
  right: 20,
   borderStyle:Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
   returnKeyType:Ti.UI.RETURNKEY_DONE,
  hintText: '1000.00'
});

amountRow.add(tfAmount);

//creating the textfield for our percentage interest 
//rate input
var tfInterestRate = Ti.UI.createTextField({
  width: 140,
  height: 30,
  right: 20,
   borderStyle:Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
   returnKeyType:Ti.UI.RETURNKEY_DONE,
  value: interestRate
});

interestRateRow.add(tfInterestRate);

How it works...

In this example, we created a couple of basic textfield with a rounded border style, and introduced some new property types that don't appear in labels and imageviews, including hintText. The hintText property displays a value in the textfield, which disappears when that textfield has focus (for example, when a user taps it to enter some data using their keyboard).

The user input is available in the textfield property called value; as you must have noted in the preceding recipe, accessing this value is simply a matter of assigning it to a variable (for example, var myName = txtFirstName.value), or using the value property directly.

There's more...

textfield are one of the most common components in any application, and in Titanium there are a couple of points and options to consider whenever you use them.

Retrieving text

It's important to note that when you want to retrieve the text that a user has typed in a textfield, you need to reference the value property and not the text, like many of the other string-based controls!

Experimenting with other textfield border styles

Try experimenting with other textfield border styles to give your app a different appearance. Other possible values are the following:

Ti.UI.INPUT_BORDERSTYLE_BEZEL
Ti.UI.INPUT_BORDERSTYLE_LINE
Ti.UI.INPUT_BORDERSTYLE_NONE
Ti.UI.INPUT_BORDERSTYLE_ROUNDED

Working with keyboards and keyboard toolbars

When a textfield or textarea control gains focus in either an iPhone or an Android phone, the default keyboard is what you see spring up on the screen. There will be times, however, when you wish to change this behavior; for example, you may only want to have the user input numeric characters into a textfield when they are providing a numerical amount (such as their age or a monetary value). Additionally, keyboard toolbars can be created to appear above the keyboard itself, which will allow you to provide the user with other options, such as removing the keyboard from the window, or allowing copy and paste operations via a simple button tap.

In the following recipe, we're going to create a toolbar that contains both a system button and another system component called flexiblespace. These will be added at the top of our numeric keyboard, which will appear whenever the TextField for amount or interest rate gains focus. Note that in this example, we have updated the tfAmount and tfInterestRate textfield objects to contain the keyboardType and returnKeyType properties.

Getting started

Note that toolbars are iOS-specific, and currently they may not be available for Android in the Titanium SDK.

How to do it...

Open your app.js file and type the following code. If you have been following along from the previous recipe, this code should replace the previous recipe's code for adding the amount and interest rate textfields:

//flexible space for button bars
var flexSpace = Ti.UI.createButton({
  systemButton:Ti.UI.iPhone.SystemButton.FLEXIBLE_SPACE
});
 
//done system button
var buttonDone = Ti.UI.createButton({
    systemButton:Ti.UI.iPhone.SystemButton.DONE,
    bottom: 0
});

//add the event listener 'click' event to our done button
buttonDone.addEventListener('click', function(e){
    tfAmount.blur();
    tfInterestRate.blur();
    interestRate = tfInterestRate.value;
});

//creating the textfield for our loan amount input
var tfAmount = Ti.UI.createTextField({
    width: 140,
    height: 30,
    right: 20,
    borderStyle:Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
    returnKeyType:Ti.UI.RETURNKEY_DONE,
    hintText: '1000.00',
    keyboardToolbar: [flexSpace,buttonDone],
    keyboardType:Ti.UI.KEYBOARD_PHONE_PAD
});
amountRow.add(tfAmount);

//creating the textfield for our percentage interest rate //input
var tfInterestRate = Ti.UI.createTextField({
    width: 140,
    height: 30,
    right: 20,
    borderStyle:Ti.UI.INPUT_BORDERSTYLE_ROUNDED,
    returnKeyType:Ti.UI.RETURNKEY_DONE,
    value: interestRate,
    keyboardToolbar: [flexSpace,buttonDone],
    keyboardType:Ti.UI.KEYBOARD_PHONE_PAD
});

interestRateRow.add(tfInterestRate);

How it works...

In this recipe, we created a textfield and added it to our view. You should have noticed by now how many properties are universal among the different UI components: width, height, top, and right are just four properties that are used in our textfield called tfAmount and were used in previous recipes for other components.

Many touchscreen phones do not have physical keyboards; however, we are using a touchscreen keyboard to gather our input data. Depending on the data you require, you may not need a full keyboard with all the QWERTY keys, and you may want to just display a numeric keyboard, for example, if you were using the telephone dialing features on your iPhone or Android device.

Additionally, you may require the QWERTY keys, but in a specific format. A custom keyboard makes the user input quicker and less frustrating for the user by presenting custom options, such as keyboards for inputting web addresses and e-mails with all the www and @ symbols in convenient touch locations.

In this example, we're setting keyboardType to Ti.UI.KEYBOARD_PHONE_PAD, which means that whenever the user clicks on that field, they see a numeric keypad.

In addition, we are specifying the keyboardToolbar property to be an array of our Done button as well as the the flexspace button, so we get a toolbar with the Done button. The event listener added to the Done button ensures that we can pick up the click, capture the values, and blur the field, essentially hiding the keypad.

Tip

Downloading the example code

You can download the example code files from your account at http://www.packtpub.com for all the Packt Publishing books you have purchased. If you purchased this book elsewhere, you can visit http://www.packtpub.com/support and register to have the files e-mailed directly to you.

How it works...

There's more

Try experimenting with other keyboard styles in your Titanium app!

Experimenting with keyboard styles

Other possible values are shown here:

Ti.UI.KEYBOARD_DEFAULT
Ti.UI.KEYBOARD_EMAIL
Ti.UI.KEYBOARD_ASCII
Ti.UI.KEYBOARD_URL
Ti.UI.KEYBOARD_NUMBER_PAD
Ti.UI.KEYBOARD_NUMBERS_PUNCTUATION
Ti.UI.KEYBOARD_PHONE_PAD

Enhancing your app with sliders and switches

Sliders and switches are two UI components that are simple to implement and can bring that extra level of interactivity into your apps. Switches, as the name suggests, have only two states—on and off—which are represented by boolean values (true and false).

Sliders, on the other hand, take two float values—a minimum value and a maximum value—and allow the user to select any number between and including these two values. In addition to its default styling, the slider API also allows you to use images for both sides of the track and the slider thumb image that runs along it. This allows you to create some truly customized designs.

We are going to add a switch to indicate an on/off state and a slider to hold the loan length, with values ranging from a minimum of 6 months to a maximum of 72 months. Also, we'll add some event handlers to capture the changed value from each component, and in the case of the slider, we will update an existing label with the new slider value. Don't worry if you aren't yet 100 percent sure about how event handlers work, as we'll cover them in further detail in Chapter 6, Getting to Grips With Properties and Events.

How to do it...

If you're following with the LoanCalc app, the next code should replace the code in your window2.js file. We'll also add a label to identify what the switch component does and a view component to hold it all together:

//create an instance of a window
module.exports = (function(){
var win = Ti.UI.createWindow({
  backgroundColor: '#BBB',
  title: 'Settings'
});

//create the view, this will hold all of our UI controls 
var view = Ti.UI.createView({
  width: 300,
  height: 70,
  left: 10,
  top: 10,
  backgroundColor: '#fff',
  borderRadius: 5
});

//create a label to identify the switch control to the user
var labelSwitch = Ti.UI.createLabel({
    width: Ti.UI.SIZE,
    height: 30,
    top: 20,
    left: 20,
    font: {fontSize: 14, fontFamily: 'Helvetica', 
          fontWeight: 'bold'},
    text: 'Auto Show Chart?'
});
view.add(labelSwitch);

//create the switch object
var switchChartOption = Ti.UI.createSwitch({
  right: 20,
  top: 20,
  value: false
});
view.add(switchChartOption);


win.add(view);

return win;
})();

Now let's write the slider code; go back to your app.js file and type the following code underneath the interestRateRow.add(tfInterestRate); line:

//create the slider to change the loan length
var lengthSlider = Ti.UI.createSlider({
  width: 140,
  top: 200,
  right: 20,
  min: 12,
  max: 60,
  value: numberMonths,
  thumbImage: 'sliderThumb.png',
  highlightedThumbImage: 'sliderThumbSelected.png'
});

lengthSlider.addEventListener('change', function(e){
  //output the value to the console for debug
   console.log(lengthSlider.value); 
   //update our numberMonths variable
  numberMonths = Math.round(lengthSlider.value); 
   //update label
  labelLoanLength.text = 'Loan length (' + Math.round(numberMonths) + ' months):';
});

loanLengthRow.add(lengthSlider);

How it works...

In this recipe, we added two new components to two separate views within two separate windows. The first component—a switch—is fairly straightforward, and apart from the standard layout and positioning properties, it takes one main boolean value to determine its on or off status. It also has only one event, change, which is executed whenever the switch changes from the on to off position or vice versa.

On the Android platform, the switch can be altered to appear as a toggle button (default) or a checkbox. Additionally, Android users can display a text label using the title property, which can be changed programmatically by using the titleOff and titleOn properties.

The slider component is more interesting and has many more properties than a Switch. sliders are useful for instances where we want to allow the user to choose between a range of values; in this case, it is a numeric range of months from 12 to 60. This is a much more effective method of choosing a number from a range than listing all the possible options in a picker, and is much safer than letting a user enter possibly invalid values via a textfield or textarea component.

Pretty much all of the slider can be styled using the default properties available in the Titanium API, including thumbImage and highlightedThumbImage, as we did in this recipe. The highlightedThumbImage property allows you to specify the image that is used when the slider is being selected and used, allowing you to have a default and an active state.

How it works...

There's more…

Try extending the styling of the slider component using images for the left- and right-hand sides of the track, which is the element that runs horizontally underneath the moving switch.

Passing custom variables between windows

You'll often find a need to pass variables and objects between different screen objects in your apps, such as windows, in your apps. One example is between a master and a child view. If you have a tabular list of data that shows only a small amount of information per row, and you wish to view the full description, you might pass that description data as a variable to the child window.

In this recipe, we're going to apply this very principle to a variable on the settings window (in the second tab of our LoanCalc app), by setting the variable in one window and then passing it back for use in our main window.

How to do it...

Under the declaration for your second window, win2 in the app.js file, include the following additional property called autoShowChart and set it to false. This is a custom property, that is, a property that is not already defined by the Titanium API. Often, it's handy to include additional properties in your objects if you require certain parameters that the API doesn't provide by default:

//set the initial value of win2's custom property
win2.autoShowChart = false;

Now, in the window2.js file, which holds all the subcomponents for your second window, replace the code that you created earlier to add the switch with the following code. This will update the window's autoShowChart variable whenever the switch is changed:

//create the switch object
var switchChartOption = Ti.UI.createSwitch({
  right: 20,
  top: 20,
  value: false
});

//add the event listener for the switch when it changes
switchChartOption.addEventListener('change', function(e){
  win.autoShowChart = switchChartOption.value;
});

//add the switch to the view
view.add(switchChartOption);

How it works…

How this code works is actually pretty straightforward. When an object is created in Titanium, all the standard properties are accessible in a dictionary object of key-value pairs; all that we're doing here is extending that dictionary object to add a property of our own.

We can do this in two ways. As shown in our recipe's source code, this can be done after the instantiation of the window object, or it can also be done immediately within the instantiation code. In the source code of the second window, we are simply referencing the same object, so all of its properties are already available for us to read from and write to.

There's more...

There are other ways of passing and accessing objects and variables between Windows, including the use of App Properties and Events. These will be covered in Chapter 6, Getting to Grips with Properties and Events.

Creating buttons and capturing click events

In any given app, you'll notice that creating buttons and capturing their click events is one of the most common tasks you do. This recipe will show you how to declare a button control in Titanium and attach a click event to it. Within that click event, we'll perform a task and log it to the info window in Appcelerator Studio.

This recipe will also demonstrate how to implement some of the default styling mechanisms available for you via the API.

How to do it...

Open your app.js file and type the following code. If you're following along with the LoanCalc app, the following code should go after you created and added the textfield controls:

//calculate the interest for this loan button
var buttonCalculateInterest = Ti.UI.createButton({
   title: 'Calculate Total Interest',
  id: 1,
  top: 10
});

//add the event listener
buttonCalculateInterest.addEventListener('click', calculateAndDisplayValue);

//add the first button to our view
view.add(buttonCalculateInterest);

//calculate the interest for this loan button
var buttonCalculateRepayments = Ti.UI.createButton({
   title: 'Calculate Total Repayment',
  id: 2,
  top: 10
});

//add the event listener
buttonCalculateRepayments.addEventListener('click', 
                          calculateAndDisplayValue);

//add the second and final button to our view
view.add(buttonCalculateRepayments);

Now that we've created our two buttons and added the event listeners, let's create the calculateAndDisplayValue() function to do some simple fixed interest mathematics and produce the results, which we'll log to the Appcelerator Studio console:

//add the event handler which will be executed when either of //our calculation buttons are tapped
function calculateAndDisplayValue(e)
{
   //log the button id so we can debug which button was tapped
  console.log('Button id = ' + e.source.id);

    if (e.source.id == 1) 
    {
       //Interest (I) = Principal (P) times Rate Per Period 
       //(r) times Number of Periods (n) / 12 
       var totalInterest = (tfAmount.value * (interestRate / 
       100) * numberMonths) / 12;
        
      //log result to console
      console.log('Total Interest = ' + totalInterest);
    }
    else 
    {
      //Interest (I) = Principal (P) times Rate Per Period (r) 
      //times Number of Periods (n) / 12 
      var totalInterest = (tfAmount.value * (interestRate / 
      100) * numberMonths) / 12;
      
      var totalRepayments = Math.round(tfAmount.value) +  
      totalInterest;
      
      //log result to console
      console.log('Total repayments' + totalRepayments);
    }

} //end function

How it works...

Most controls in Titanium are capable of firing one or more events, such as focus, onload, or (as in our recipe) click. The click event is undoubtedly the one you'll use more often than any other. In the preceding source code, you will notice that, in order to execute code from this event, we are adding an event listener to our button, which has a signature of click. This signature is a string and forms the first part of our event listener. The second part is the executing function for the event.

It's important to note that other component types can also be used in a similar manner; for example, an imageview can be declared. It can contain a custom button image, and can have a click event attached to it in exactly the same way as a regular button can.

How it works...

Informing your users with dialogs and alerts

There are a number of dialogs available for you to use in the Titanium API, but for the purposes of this recipe, we'll be concentrating on the two main ones: alert dialog and option dialog. These two simple components perform two similar roles, but with a key difference. The alert dialog is normally used only to show the user a message, while the option dialog asks the user a question and can accept a response in the form of a number of options. Generally, an alert dialog only allows a maximum of two responses from the user, whereas the option dialog can contain many more.

There are also key differences in the layout of these two dialog components, which will become obvious in the following recipe.

How to do it…

First, we'll create an alert dialog that simply notifies the user of an action that can not be completed due to missing information. In our case, that they have not provided a value for the loan amount in tfAmount TextField. Add the following code to the calculateAndDisplayValue() function, just under the initial console.log command:

if (tfAmount.value === '' || tfAmount.value === null) 
{
    var errorDialog = Ti.UI.createAlertDialog({
      title: 'Error!',
      message: 'You must provide a loan amount.'
    });
    errorDialog.show();
return;
}

Now let's add the option dialog. This is going to display the result from our calculation and then give the user the choice of viewing the results as a pie chart (in a new window), or of canceling and staying on the same screen.

We need to add a couple of lines of code to define the optionsMessage variable that will be used in the option dialog, so add this code below the line calculating totalRepayments:

console.log('Total repayments = ' + totalRepayments) :
var optionsMessage = "Total repayments on this loan equates to $" + totalRepayments;

Then add the following code just below the line of code defining totalInterest:

console.log('Total interest = ' + totalInterest) :
var optionsMessage = "Total interest on this loan equates to $" + totalInterest;

Finally, at the end of the function, add this code:

//check our win2 autoShowChart boolean value first (coming //from the switch on window2.js)
if (win2.autoShowChart == true) {
   // openChartWindow();
 }
 else {
  var resultOptionDialog = Ti.UI.createOptionDialog({
        title: optionsMessage + '\n\nDo you want to 
                  view this in a chart?',
        options: ['Okay', 'No'],
        cancel: 1
  });
  
  //add the click event listener to the option dialog
  resultOptionDialog.addEventListener('click', function(e){
    console.log('Button index tapped was: ' + e.index);
    if (e.index == 0) 
      {
       // openChartWindow();
    }
  });
      
  resultOptionDialog.show();

} //end if

How it works...

The alert dialog, in particular, is a very simple component that simply presents the user with a message as a modal, and it has only one possible response, which closes the alert. Note that you should be careful not to call an alert dialog more than once while a pending alert is still visible, for example, if you're calling that alert from within a loop.

The option dialog is a much larger modal component that presents a series of buttons with a message at the bottom of the screen. It is generally used to allow the user to pick more than one item from a selection. In our code, resultOptionDialog presents the user with a choice of two options—Okay and No. One interesting property of this dialog is Cancel, which dismisses the dialog without firing the click event, and also styles the button at the requested index in a manner that differentiates it from the rest of the group of buttons.

Note that we've commented out the openChartWindow() function because we haven't created it yet. We'll be doing that in the next recipe.

Just like the Window object, both of these dialogs are not added to another View, but are presented by calling the show() method instead. You should call the show() method only after the dialog has been properly instantiated and any event listeners have been created.

The following images show the difference between the alert dialog and the option dialog:

How it works...

There's more...

You can also create a predefined alert dialog using basic JavaScript, by using the alert('Hello world!'); syntax. Be aware, however, that you only have control over the contents of the messages that use this method, and the title of your alertdialog will always be set to Alert.

Creating charts using Raphael JS

Let's finish off our calculations visually by displaying charts and graphs. Titanium lacks a native charting API. However, there are some open source options for implementing charts, such as Google Charts. While the Google solution is free, it requires your apps to be online every time you need to generate a chart. This might be okay for some circumstances, but it is not the best solution for an application that is meant to be usable offline. Plus, Google Charts returns a generated JPG or PNG file at the requested size and in rasterized format, which is not great for zooming in when viewing on an iPhone or iPad.

A better solution is to use the open source and MIT-licensed Raphael library, which (luckily for us) has a charting component! It is not only free but also completely vector-based, which means any charts that you create will look great in any resolution, and can be zoomed in to without any loss of quality.

Note

Note that this recipe may not work on all Android devices. This is because the current version of Raphael isn't supported by non-WebKit mobile browsers. However, it will work as described here for iOS.

Getting ready

  1. Download the main Raphael JS library from http://raphaeljs.com. The direct link is http://github.com/DmitryBaranovskiy/raphael/raw/master/raphael-min.js.
  2. Download the main Charting library from http://g.raphaeljs.com (the direct link is http://github.com/DmitryBaranovskiy/g.raphael/blob/master/min/g.raphael-min.js?raw=true), and any other charting libraries that you wish to use.
  3. Download the Pie Chart library, which is at http://github.com/DmitryBaranovskiy/g.raphael/blob/master/min/g.pie-min.js?raw=true.

How to do it...

If you're following along with the LoanCalc example app, then open your project directory and put your downloaded files into a new folder called charts under the Resources directory. You can put them into the root folder if you wish, but bear in mind that you will have to ensure that your references in the following steps are correct.

To use the library, we'll be creating a webview in our app, referencing a variable that holds the HTML code to display a Raphael chart, which we'll call chartHTML. A webview is a UI component that allows you to display web pages or HTML in your application. It does not include any features of a full-fledged browser, such as navigation controls or address bars.

Create a new file called chartwin.js in the Resources directory and add the following code to it:

//create an instance of a window
module.exports = (function() {

  var chartWin = Ti.UI.createWindow({
    title : 'Loan Pie Chart'
  });

  chartWin.addEventListener("open", function() {
    
    //create the chart title using the variables we passed in from
    //app.js (our first window)
    var chartTitleInterest = 'Total Interest: $' + chartWin.totalInterest;
    var chartTitleRepayments = 'Total Repayments: $' + chartWin.totalRepayments;
      
    //create the chart using the sample html from the
    //raphaeljs.com website
    var chartHTML = '<html><head> <title>RaphaelJS Chart</title><meta name="viewport" content="width=device-width, initial-scale=1.0"/>      <script src="charts/raphael-min.js" type="text/javascript" charset="utf-8"></script>    <script src="charts/g.raphael-min.js" type="text/javascript" charset="utf-8"></script>    <script src="charts/g.pie-min.js" type="text/javascript" charset="utf-8"></script>    <script type="text/javascript" charset="utf-8"> window.onload = function () { var r = Raphael("chartDiv");  r.text.font = "12px Verdana, Tahoma, sans-serif";  r.text(150, 10, "';

    chartHTML = chartHTML + chartTitleInterest + '").attr({"font-size": 14}); r.text(150, 30, "' + chartTitleRepayments + '").attr({"font-size": 14});';

    chartHTML = chartHTML + ' r.piechart(150, 180, 130, [' + Math.round(chartWin.totalInterest) + ',' + Math.round(chartWin.principalRepayments) + ']); };
</script> </head><body>     <div id="chartDiv" style="width:320px; height: 320px; margin: 0"></div> </body></html>';

    //add a webview to contain our chart
    var webview = Ti.UI.createWebView({
      width : Ti.UI.FILL,
      height : Ti.UI.FILL,
      top : 0,
      html : chartHTML
    });
    
    chartWin.add(webview);

  });

  return chartWin;

})();

Now, back in your app.js file, create a new function at the end of the file, called openChartWindow(). This function will be executed when the user chooses Okay from the previous recipe's option dialog. It will create a new window object based on the chartwin.js file and pass to it the values needed to show the chart:

//we'll call this function if the user opts to view the loan //chart
function openChartWindow() {

  //Interest (I) = Principal (P) times Rate Per Period (r)
  //times Number of Periods (n) / 12
  var totalInterest = (tfAmount.value * (interestRate / 100) * numberMonths) / 12;
  var totalRepayments = Math.round(tfAmount.value) + totalInterest;
  
  
  var chartWindow = require("chartwin");

  chartWindow.numberMonths = numberMonths;
  chartWindow.interestRate = interestRate;
  chartWindow.totalInterest = totalInterest;
  chartWindow.totalRepayments = totalRepayments;
  chartWindow.principalRepayments = (totalRepayments - totalInterest);
    

  tab1.open(chartWindow);

}

Finally, remember to uncomment the two // openChartWindow() lines that you added in the previous recipe. Otherwise, you won't see anything!

How it works...

Essentially, what we're doing here is wrapping the Raphael library, something that was originally built for the desktop browser, into a format that can be consumed and displayed using the iOS's WebKit browser. You can find out more about Raphael at http://raphaeljs.com and http://g.raphaeljs.com, and learn how it renders charts via its JavaScript library. We'll not be explaining this in detail; rather, we will cover the implementation of the library to work with Titanium.

Our implementation consists of creating a webview component that (in this case) will hold the HTML data that we constructed in the chartHTML variable. This HTML data contains all of the code that is necessary to render the charts, including the scripts listed in item #2 of the Getting Ready section of this recipe. If you have a chart with static data, you can also reference the HTML from a file using the url property of the webview object, instead of passing all the HTML as a string.

The chart itself is created using some simple JavaScript embedded in the r.piechart(150, 180, 130, n1, n2) HTML data string, where n1 and n2 are the two values we wish to display as slices in the pie chart. The other values define the center point of the chart from the top and left, respectively, followed by the chart radius.

All of this is wrapped up in a new module file defined by the chartwin.js file, which accesses the properties passed from the first tab's window in our LoanCalc app. This data is passed using exactly the same mechanism as explained in a previous recipe, Passing custom variables between Windows.

Finally, the chart window is passed back to the app.js file, within the openChartWindow() function, and from there, we use tab1.open() to open a new window within tab1. This has the effect of sliding the new window, similar to the way in which many iOS apps work (in Android, the new window would open normally).

The following screenshot shows the Raphael JS Library being used to show a pie chart based on our loan data:

How it works...

Creating an actionbar in Android

In Android 3.0, Google introduced the actionbar, a tab-style interface that sits under the title bar of an application. The actionbar behaves a lot like the tabgroup, which we're used to in iOS, and coincidently it can be created in the same way as we created a TabGroup previously, which makes it very easy to create one! All that we need to do is make some minor visual tweaks in our application to get it working on Android.

You will be running this recipe on Android 4.x, so make sure you're running an emulator or device that runs 4.x or higher. I'd recommend using GenyMotion, available at http://www.genymotion.com, to emulate Android. It's fast and way more flexible than, the built-in Android SDK emulators. It's also fully supported in Titanium and in Appcelerator Studio.

The complete source code for this chapter can be found in the /Chapter 1/LoanCalc folder.

How to do it...

There's not much to do to get the actionbar working, as we've already created a tabgroup for our main interface. We just need to do just a few tweaks to our app views, buttons, and labels.

First, let's make sure that all our labels are rendering correctly. Add the following attribute to any label that you've created:

color: '#000'

Now we need to fix our buttons. Let's add a tweak to them after we've created them (for Android only). Add the following code after your buttons. To do this, we're going to use .applyProperties, which allows us to make multiple changes to an element at the same time:

if (Ti.Platform.osname.toLowerCase() === 'android') {
  buttonCalculateRepayments.applyProperties({
    color : '#000',    
    height : 45
  });
  
  buttonCalculateInterest.applyProperties({
    color : '#000',    
    height : 45
  });
}

This block checks whether we're running Android and makes some changes to the buttons. Let's add some more code to the block to adjust the textfield height as well, as follows:

if (Ti.Platform.osname.toLowerCase() === 'android') {
  buttonCalculateRepayments.applyProperties({
    color : '#000',
    height : 45
  });

  buttonCalculateInterest.applyProperties({
    color : '#000',
    height : 45
  });

  tfAmount.applyProperties({
    color : '#000',
    height : 35
  });
  
  tfInterestRate.applyProperties({
    color : '#000',
    height : 35
  });
}

Finally, we're going to make a tweak to our settings window to make it play nicely on Android devices with different widths. Edit the window2.js file and remove the width of the view variable, changing it to the following:

var view = Ti.UI.createView({
    height : 70,
    left : 10,
right: 10,
    top : 10,
    backgroundColor : '#fff',
    borderRadius : 5
});

We'll need to update the labelSwitch variable too, by adding this line:

color: '#000'

Now let's run the app in the Android emulator or on a device, and we should see the following:

How to do it...

How it works...

We've not done much here to get an actionbar working. That's because Titanium takes care of the heavy lifting for us. You must have noticed that the only changes we made were visual tweaks to the other elements on the screen; the actionbar just works!

This is a really nice feature of Titanium, wherein you can create one UI element, a tabgroup, and have it behave differently for iOS and Android using the same code.

Having said that, there are some additional tweaks that you can do to your actionbar using the Ti.Android.ActionBar API. This gives specific access to properties and events associated with the actionbar. More information can be found at http://docs.appcelerator.com/platform/latest/#!/api/Titanium.Android.ActionBar.

So, for example, you can change the properties of actionBar by accessing it via the current window:

actionBar = win.activity.actionBar; 

if (actionBar) {
actionBar.backgroundImage = "/bg.png";
actionBar.title = "New Title"; 
}

As you can see, it's really easy to create an actionbar using a tabgroup and alter its properties in Android.

Left arrow icon Right arrow icon

Key benefits

  • Leverage your JavaScript skills to write mobile applications using Titanium Studio tools with the native advantage
  • Deploy your application on the App Store and Google Play
  • Add your own IOS native modules in objective-C, in an easy-to-follow step-by-step format

Description

This book will take you through the process of building cross-platform, native UI applications for the mobile from scratch. You will learn how to develop apps, how to use GPS, cameras and photos and how to build socially connected apps. You will also learn how to package them for submission to the App Store and Google Play. This cookbook takes a pragmatic approach to creating applications in JavaScript from putting together basic UIs, to handling events and implementation of third party services such as Twitter, Facebook and Push notifications. The book shows you how to integrate datasources and server APIs, and how to use local databases. The topics covered will guide you to use Appcelerator Studio tools for all the mobile features such as Geolocation, Accelerometer, animation and more. You’ll also learn about Alloy, the Appcelerator MVC framework for rapid app development, and how to transfer data between applications using URLSchemes, enabling other developers to access and launch specific parts of your app. Finally, you will learn how to register developer accounts and publish your very own applications on the App Store and Google Play.

Who is this book for?

This book is an essential for any developer learning or using JavaScript who wants to write native UI applications for iOS and Android. No knowledge of Objective-C, Swift and Java is required and you’ll quickly be developing native, cross-platform apps, in JavaScript!

What you will learn

  • Transfer data between applications with URL schemes, and make your application accessible to other mobile applications and services
  • Connect with remote services using JSON
  • Work with Google Maps and Apple Maps, GPS and annotate routes
  • Create animations and special effects
  • Integrate notifications and connect with social media services such as Facebook and Twitter
  • Build applications with Alloy MVC – a rapid application development framework
  • Design native APIs and use local databases
Estimated delivery fee Deliver to Philippines

Standard delivery 10 - 13 business days

₱492.95

Premium delivery 5 - 8 business days

₱2548.95
(Includes tracking information)

Product Details

Country selected
Publication date, Length, Edition, Language, ISBN-13
Publication date : Nov 30, 2015
Length: 368 pages
Edition : 1st
Language : English
ISBN-13 : 9781849697705
Category :
Languages :

What do you get with Print?

Product feature icon Instant access to your digital eBook copy whilst your Print order is Shipped
Product feature icon Paperback book shipped to your preferred address
Product feature icon Download this book in EPUB and PDF formats
Product feature icon Access this title in our online reader with advanced features
Product feature icon DRM FREE - Read whenever, wherever and however you want
OR
Modal Close icon
Payment Processing...
tick Completed

Shipping Address

Billing Address

Shipping Methods
Estimated delivery fee Deliver to Philippines

Standard delivery 10 - 13 business days

₱492.95

Premium delivery 5 - 8 business days

₱2548.95
(Includes tracking information)

Product Details

Publication date : Nov 30, 2015
Length: 368 pages
Edition : 1st
Language : English
ISBN-13 : 9781849697705
Category :
Languages :

Packt Subscriptions

See our plans and pricing
Modal Close icon
$19.99 billed monthly
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Simple pricing, no contract
$199.99 billed annually
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₱260 each
Feature tick icon Exclusive print discounts
$279.99 billed in 18 months
Feature tick icon Unlimited access to Packt's library of 7,000+ practical books and videos
Feature tick icon Constantly refreshed with 50+ new titles a month
Feature tick icon Exclusive Early access to books as they're written
Feature tick icon Solve problems while you work with advanced search and reference features
Feature tick icon Offline reading on the mobile app
Feature tick icon Choose a DRM-free eBook or Video every month to keep
Feature tick icon PLUS own as many other DRM-free eBooks or Videos as you like for just ₱260 each
Feature tick icon Exclusive print discounts

Frequently bought together


Stars icon
Total 7,808.97
Appcelerator Titanium Application Development by Example Beginner's Guide
₱2806.99
Appcelerator Titanium Smartphone App Development Cookbook Second Edition
₱2500.99
Creating Mobile Apps with Appcelerator Titanium
₱2500.99
Total 7,808.97 Stars icon
Banner background image

Table of Contents

15 Chapters
1. Building Apps Using Native UI Components Chevron down icon Chevron up icon
2. Working with Local and Remote Data Sources Chevron down icon Chevron up icon
3. Integrating Maps and GPS Chevron down icon Chevron up icon
4. Enhancing Your Apps with Audio, Video, and Cameras Chevron down icon Chevron up icon
5. Connecting Your Apps to Social Media and E-mail Chevron down icon Chevron up icon
6. Getting to Grips with Properties and Events Chevron down icon Chevron up icon
7. Creating Animations, Transformations and Implementing Drag and Drop Chevron down icon Chevron up icon
8. Interacting with Native Phone Applications and APIs Chevron down icon Chevron up icon
9. Integrating Your Apps with External Services Chevron down icon Chevron up icon
10. Extending Your Apps with Custom Modules Chevron down icon Chevron up icon
11. Platform Differences, Device Information, and Quirks Chevron down icon Chevron up icon
12. Preparing Your App for Distribution and Getting It Published Chevron down icon Chevron up icon
13. Implementing and Using URL Schemes Chevron down icon Chevron up icon
14. Introduction to Alloy MVC Chevron down icon Chevron up icon
Index Chevron down icon Chevron up icon

Customer reviews

Rating distribution
Full star icon Full star icon Full star icon Full star icon Full star icon 5
(4 Ratings)
5 star 100%
4 star 0%
3 star 0%
2 star 0%
1 star 0%
Adam A. Dec 09, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Jason is well known in the Appcelerator Community for his top-notch work. This book was everything I expected and more. Whether you are new to Appcelerator or a seasoned veteran - this book has something to offer you. I plan to use this book as a benchmark for all new hires to my team.
Amazon Verified review Amazon
ade Dec 11, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Very well written. Great recipes that will prove useful to people to both people new to the appcelerator platform or people with more experience. Well worth the purchase to have to hand.
Amazon Verified review Amazon
Amazon Customer Dec 03, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
A very practical book containing many recipes you will definitely use in your apps. From simple to more complex, something for everyone!
Amazon Verified review Amazon
Jose Manuel Cerrejon Dec 09, 2015
Full star icon Full star icon Full star icon Full star icon Full star icon 5
Jason Kneen is a great author and I read his first Edition with enthusiasm. It teaches you some tips with their great recipes. Now in this second edition write code based in Alloy, too. It's easy to follow a recipe step by step and achieve your goal. Very clear and recommended if you are an experienced Titanium user or a web developer who want to write Mobile apps with Javascript code using native UI components running on Android, iOS and Windows Phone.
Amazon Verified review Amazon
Get free access to Packt library with over 7500+ books and video courses for 7 days!
Start Free Trial

FAQs

What is the delivery time and cost of print book? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela
What is custom duty/charge? Chevron down icon Chevron up icon

Customs duty are charges levied on goods when they cross international borders. It is a tax that is imposed on imported goods. These duties are charged by special authorities and bodies created by local governments and are meant to protect local industries, economies, and businesses.

Do I have to pay customs charges for the print book order? Chevron down icon Chevron up icon

The orders shipped to the countries that are listed under EU27 will not bear custom charges. They are paid by Packt as part of the order.

List of EU27 countries: www.gov.uk/eu-eea:

A custom duty or localized taxes may be applicable on the shipment and would be charged by the recipient country outside of the EU27 which should be paid by the customer and these duties are not included in the shipping charges been charged on the order.

How do I know my custom duty charges? Chevron down icon Chevron up icon

The amount of duty payable varies greatly depending on the imported goods, the country of origin and several other factors like the total invoice amount or dimensions like weight, and other such criteria applicable in your country.

For example:

  • If you live in Mexico, and the declared value of your ordered items is over $ 50, for you to receive a package, you will have to pay additional import tax of 19% which will be $ 9.50 to the courier service.
  • Whereas if you live in Turkey, and the declared value of your ordered items is over € 22, for you to receive a package, you will have to pay additional import tax of 18% which will be € 3.96 to the courier service.
How can I cancel my order? Chevron down icon Chevron up icon

Cancellation Policy for Published Printed Books:

You can cancel any order within 1 hour of placing the order. Simply contact customercare@packt.com with your order details or payment transaction id. If your order has already started the shipment process, we will do our best to stop it. However, if it is already on the way to you then when you receive it, you can contact us at customercare@packt.com using the returns and refund process.

Please understand that Packt Publishing cannot provide refunds or cancel any order except for the cases described in our Return Policy (i.e. Packt Publishing agrees to replace your printed book because it arrives damaged or material defect in book), Packt Publishing will not accept returns.

What is your returns and refunds policy? Chevron down icon Chevron up icon

Return Policy:

We want you to be happy with your purchase from Packtpub.com. We will not hassle you with returning print books to us. If the print book you receive from us is incorrect, damaged, doesn't work or is unacceptably late, please contact Customer Relations Team on customercare@packt.com with the order number and issue details as explained below:

  1. If you ordered (eBook, Video or Print Book) incorrectly or accidentally, please contact Customer Relations Team on customercare@packt.com within one hour of placing the order and we will replace/refund you the item cost.
  2. Sadly, if your eBook or Video file is faulty or a fault occurs during the eBook or Video being made available to you, i.e. during download then you should contact Customer Relations Team within 14 days of purchase on customercare@packt.com who will be able to resolve this issue for you.
  3. You will have a choice of replacement or refund of the problem items.(damaged, defective or incorrect)
  4. Once Customer Care Team confirms that you will be refunded, you should receive the refund within 10 to 12 working days.
  5. If you are only requesting a refund of one book from a multiple order, then we will refund you the appropriate single item.
  6. Where the items were shipped under a free shipping offer, there will be no shipping costs to refund.

On the off chance your printed book arrives damaged, with book material defect, contact our Customer Relation Team on customercare@packt.com within 14 days of receipt of the book with appropriate evidence of damage and we will work with you to secure a replacement copy, if necessary. Please note that each printed book you order from us is individually made by Packt's professional book-printing partner which is on a print-on-demand basis.

What tax is charged? Chevron down icon Chevron up icon

Currently, no tax is charged on the purchase of any print book (subject to change based on the laws and regulations). A localized VAT fee is charged only to our European and UK customers on eBooks, Video and subscriptions that they buy. GST is charged to Indian customers for eBooks and video purchases.

What payment methods can I use? Chevron down icon Chevron up icon

You can pay with the following card types:

  1. Visa Debit
  2. Visa Credit
  3. MasterCard
  4. PayPal
What is the delivery time and cost of print books? Chevron down icon Chevron up icon

Shipping Details

USA:

'

Economy: Delivery to most addresses in the US within 10-15 business days

Premium: Trackable Delivery to most addresses in the US within 3-8 business days

UK:

Economy: Delivery to most addresses in the U.K. within 7-9 business days.
Shipments are not trackable

Premium: Trackable delivery to most addresses in the U.K. within 3-4 business days!
Add one extra business day for deliveries to Northern Ireland and Scottish Highlands and islands

EU:

Premium: Trackable delivery to most EU destinations within 4-9 business days.

Australia:

Economy: Can deliver to P. O. Boxes and private residences.
Trackable service with delivery to addresses in Australia only.
Delivery time ranges from 7-9 business days for VIC and 8-10 business days for Interstate metro
Delivery time is up to 15 business days for remote areas of WA, NT & QLD.

Premium: Delivery to addresses in Australia only
Trackable delivery to most P. O. Boxes and private residences in Australia within 4-5 days based on the distance to a destination following dispatch.

India:

Premium: Delivery to most Indian addresses within 5-6 business days

Rest of the World:

Premium: Countries in the American continent: Trackable delivery to most countries within 4-7 business days

Asia:

Premium: Delivery to most Asian addresses within 5-9 business days

Disclaimer:
All orders received before 5 PM U.K time would start printing from the next business day. So the estimated delivery times start from the next day as well. Orders received after 5 PM U.K time (in our internal systems) on a business day or anytime on the weekend will begin printing the second to next business day. For example, an order placed at 11 AM today will begin printing tomorrow, whereas an order placed at 9 PM tonight will begin printing the day after tomorrow.


Unfortunately, due to several restrictions, we are unable to ship to the following countries:

  1. Afghanistan
  2. American Samoa
  3. Belarus
  4. Brunei Darussalam
  5. Central African Republic
  6. The Democratic Republic of Congo
  7. Eritrea
  8. Guinea-bissau
  9. Iran
  10. Lebanon
  11. Libiya Arab Jamahriya
  12. Somalia
  13. Sudan
  14. Russian Federation
  15. Syrian Arab Republic
  16. Ukraine
  17. Venezuela