In the 1st part Using Appcelerator to create your mobile applications - Part 1, we briefly discussed the benefits of creating mobile applications with this technology and explained with an example how to start a project in Alloy MVC. This sample application, which will be called MiBiblioteca, works for Android and IOS thanks to Titanium SDK.
Adding More Books to Our Mobile Library with Appcelerator Alloy
In this second part of our series (as promised in Part 1), we will focus on enhancing the application by incorporating additional books into our mobile library. We'll explore the necessary steps to modify some code, create an array of book objects, and style our application for a visually appealing experience.
1. Defining a Global Books Array
To store and manage the book collection globally, we'll define an array of objects in the Alloy.js file. This file, being the first to run in Appcelerator, is the perfect place for initializing global variables. Here's how we define the books
object:
Notice the inclusion of the image
attribute, which stores links to book cover images.
2. Updating the Model
To accommodate the new image
attribute, we need to modify the books.js model by adding a corresponding column:
3. Populating the Library
With the model and global book array ready, we can populate the library by iterating through the array and adding each book to the collection. Here's the implementation:
This for
loop ensures all the books are added to the collection.
4. Updating the User Interface
Modifying index.xml
To display the book title and cover image, we update the XML layout as follows:
Here, we use Label
for the title and ImageView
for the book cover.
Applying Styles in index.tss
The styles for the elements are defined in styles/index.tss:
Ti.UI.FILL
ensures the rows span the full width of the device.- The
height
attribute specifies the row height.
5. Handling Book Selection
To enable interaction, we modify the click event to retrieve the selected book's data using its position in the array:
6. Styling the Details View
Updating bookdetails.xml
Add an ImageView
element to display the book cover:
Adding Styles in bookdetails.tss
Define styles for the details view:
Displaying the Book Cover
In the bookdetails.js controller, pass the image URL to the ImageView
:
Final Touches and Considerations
Using Alloy MVC in Appcelerator simplifies the creation and styling of complex views while ensuring code reusability. As your application grows, leveraging community-developed widgets and modules, such as those found on gitt.io, can greatly enhance your productivity.
Tip: By maintaining a separation of views and functionality, you can support platform-specific designs (e.g., Android and iOS) without duplicating controller logic.