30
Android Programming with App Inventor for Android (draft 1, 1/2010) David Wolber

App Inventor ch1-4 - USF Computer Sciencewolber/bookChapters/App_Inventor_ch1_4.pdf · Chapter 2: Building And Deploying an App with App Inventor This chapter describes App Inventor

  • Upload
    others

  • View
    8

  • Download
    0

Embed Size (px)

Citation preview

Page 1: App Inventor ch1-4 - USF Computer Sciencewolber/bookChapters/App_Inventor_ch1_4.pdf · Chapter 2: Building And Deploying an App with App Inventor This chapter describes App Inventor

Android Programmingwith App Inventor for Android

(draft 1, 1/2010)

David Wolber

Page 2: App Inventor ch1-4 - USF Computer Sciencewolber/bookChapters/App_Inventor_ch1_4.pdf · Chapter 2: Building And Deploying an App with App Inventor This chapter describes App Inventor

Table of Contents........................................................................................................... 1Chapter 1: Introduction ...................................................................... 3

Getting Started: Downloading Some Apps.............................................. 5Chapter 2: Building And Deploying an App with App Inventor............. 6

Introduction....................................................................................... 6Building the User Interface .................................................................. 6Programming the App's Behavior .......................................................... 8Download the App to Your Phone .........................................................11Test the App in the Emulator...............................................................12Installing and Running the Emulator ....................................................12

Chapter 3: An App Is......................................................................... 15A App is a Recipe...............................................................................15An App is a Set of Event-Handlers .......................................................15An App Consists of Event-Handlers That Can Ask Questions and Branch ....17An App Consists of Event-Handlers That Can Ask Questions, Branch, andRepeat .............................................................................................18An App Consists of Event-Handlers That Can Ask Questions, Branch, Repeat,and Talk to Web Services ...................................................................19An App Consists of Event-Handlers That Can Ask Questions, Branch, Repeat,Talk to Web Services, and Remember Things ........................................20

Chapter 4: Components, Properties, Events, and Functions .............. 22Components .....................................................................................22Properties.........................................................................................24Events .............................................................................................26Functions .........................................................................................28Summary .........................................................................................29Problems..........................................................................................30

Page 3: App Inventor ch1-4 - USF Computer Sciencewolber/bookChapters/App_Inventor_ch1_4.pdf · Chapter 2: Building And Deploying an App with App Inventor This chapter describes App Inventor

Chapter 1: IntroductionProgramming is like magic to most people, and only a small percentage ofhumans ever try it. This is unfortunate, as there are many very creativepeople that don't even dream of applying their creativity, at least directly, tobuilding software. Most people consider the apps they use on theircomputers and phones as beyond their control-- they are stuck with beingconsumers, and not producers, or even "customizers", of software. Thesoftware we now use would certainly be better if the tools for building itwere accessible to more people.

There has been progress. The web started out as read-only-- only webmasters could create web pages and most of us just "consumed" theinformation out there. With blogs, wikis, social networks, and Twitter, theweb has now become a read-write web, and most everybody is now "part ofthe conversation".

However, there is still a large chasm in terms of producers and consumers:though many now blog and create web pages, there are still few who knowhow to create apps-- software that displays information dynamically and canrespond to user input and other events. Just as there is a digital divide,there is also a programmer divide that limits people's control over thedevices they use.

Can this divide be breached? Can ordinary people be taught to program theircomputers and their phones? There are reasons to believe they can. Youngpeople today are incredibly computer literate compared to the previousgenerations. They don't fear computing-- it is part of their lives from anearly age. And they use computing hours upon hours a day. Thus, they areextremely motivated to have useful software and to be able to customize itfor their own personal use.

Google is very interested in this question, and to explore it they havedesigned a new visual programming language, App Inventor, designed toallow people to program their phones. Here is Google's vision:

Mobile applications are triggering a fundamental shift in the way peopleexperience computing and use mobile phones. Ten years ago, people"went to the computer" to perform tasks and access the Internet, andthey used a cell phone only to make calls. Today, smartphones let uscarry computing with us, have become central to servicing our

Page 4: App Inventor ch1-4 - USF Computer Sciencewolber/bookChapters/App_Inventor_ch1_4.pdf · Chapter 2: Building And Deploying an App with App Inventor This chapter describes App Inventor

communication and information needs, and have made the web part ofall that we do. Ten years ago, people's use of computing was largelydissociated from real life. With the ubiquity of social networking, onlineand offline life are becoming fused. (Our) exploration is motivated bythe vision that open mobile platforms like Android can bring some ofthat same change to introductory Computer Science, to make it moreabout people and their interactions with others and with the worldaround them. It's a vision where young people—and everyone—canengage the world of mobile services and applications as creators, notjust consumers. Through this work, we hope to do the following:

• Make mobile application development accessible to anyone.• Enhance introductory learning experiences in computing through the

vehicle of Android’s open platform.• Encourage a community of faculty and students to share material and

ideas for teaching and exploring.

From Google Research Blog:http://googleresearch.blogspot.com/2009/07/app-inventor-for-android.html

The App Inventor visual language makes developing Android appsconsiderably easier than with a traditional programming language. With AppInventor, everything you can do is visible, and you program by piecingtogether blocks representing phone functionality and data. It is similar tothe Mindstorms blocks language for programming Lego robots, but youprogram your phone instead.

The blocks language makes things easier, and Google's target audience waspeople without programming experience, so ease-of-use was part of thedesign. But programming with App Inventor is still a difficult task and getsmore complex as you build more complicated apps.

The key from a learning perspective is motivation: people aresignificantly more motivated to learn programming and computer conceptsbecause they are building something fun that they can use in their everyday life. In teaching App Inventor, I've been amazed at how hard studentshave worked-- they're motivation level has been significantly higher evencompared courses in which I've taught fun programming applications likerobots or graphics. My belief is that they are more motivated because theyare building "real" software-- software that can benefit their everyday lives.

This book steps you through the process of building Android apps using AppInventor. We'll begin with some simple apps-- an app that speaks what youtype, and an app that moves a ball around the screen. But rather quickly

Page 5: App Inventor ch1-4 - USF Computer Sciencewolber/bookChapters/App_Inventor_ch1_4.pdf · Chapter 2: Building And Deploying an App with App Inventor This chapter describes App Inventor

we'll progress to more complicated apps and you'll be building games,educational software, Twitter clients, and maybe even the next killer app forthe Android platform!

Getting Started: Downloading Some Apps

The MarketThe Android Market has thousands of apps, many of which are free todownload. You can search for specific keywords to find an app, and you canread a blurb about the app and see reviews of it before downloading. Beforeembarking on our journey to learn programming, definitely download someapps and become acquainted with how Android apps look and behave.

Barcode ScannerThere are two specific apps that we'll use in the programming lessons. Thefirst is a barcode scanner. This is required because when you build an app,App Inventor creates a barcode for the app. With an Android barcode scaner,you can scan the barcode in order to install the new app on your phone.Very cool!

One popular barcode scanner is from ZXing. If you go to the Market andsearch for it, you'll find it. Just step through the installation instructions andyou'll have a barcode scanner. For fun, try scanning the ISBN barcodes ofsome books to see what the scanner does with them.

Text To SpeechThe first sample app we'll create will speak the words the user types. For this, you need tohave Text to Speech (TTS) library code on your phone. With TTS, your apps can speakwords that have been typed in or sent as a text to your phone. You candownload a TTS app named TTS Service Extended at the Android Market.

Once you've downloaded it, open the app and click on menu to choose aDefault Engine. If you don't choose an engine, the app won't work (there'sno default setting unfortunately). You can also change the default languageand speech rate.

Once you've installed it, test it by clicking on the App to start it, then clickingmenu and choosing "Listen to a preview". Then try changing to a differentlanguage to see what happens.

Page 6: App Inventor ch1-4 - USF Computer Sciencewolber/bookChapters/App_Inventor_ch1_4.pdf · Chapter 2: Building And Deploying an App with App Inventor This chapter describes App Inventor

Chapter 2: Building And Deployingan App with App InventorThis chapter describes App Inventor and steps through the task of creating,testing, and deploying a mobile app.

Introduction

Programming is generally a two-step process:

1. Design how the application will look.2. Design how the application will behave.

With App Inventor, these two tasks are performed in separate windows. Thefirst window is the Component Designer. You use it to choose and place thebuttons, text boxes, images, and other components that will appear on thephone when your app is run. The second window is the Blocks Editor. Youuse it to define the behavior of your app-- how it should respond to eventssuch as the user pressing a button.

Building the User Interface

We'll start with a simple example: an application that let's the user entersome words, then speaks the words when the user clicks a button. Thoughsimple, this application illustrates the basics of App Inventor and the basicstructure of a mobile app.

To build the application, we first open the component designer:

Page 7: App Inventor ch1-4 - USF Computer Sciencewolber/bookChapters/App_Inventor_ch1_4.pdf · Chapter 2: Building And Deploying an App with App Inventor This chapter describes App Inventor

The left side is a palette with all the components that can be added to an application. Theleft-middle panel is the surface representing the way the phone's screen will appear whenthe application runs. The programmer drags from the left to the left-middle to specify thecomponents of a particular application.

For our sample app, we need three components: a TextBox where the user can enter thewords she wants spoken, a button for the user to click, and a TextToSpeech componentthat will do the work of actually speaking the words.

The TextBox and the Button are part of the Basic palette, which is open in the snapshotabove. There are a number of other component palettes. The TextToSpeech componentis found in the Not ready for prime time palette.

The TextToSpeech component is a "non-visible" component, meaning itwon't appear on the phone's screen when the app runs. You can think of itas a little man deep within the phone who will speak out the words the user

Page 8: App Inventor ch1-4 - USF Computer Sciencewolber/bookChapters/App_Inventor_ch1_4.pdf · Chapter 2: Building And Deploying an App with App Inventor This chapter describes App Inventor

types, but will stay hidden from view.

As a component is dragged into an app, it's name appears in the middle-right list of components. By default each component is given a name thatincludes its type and a number (e.g., 'TextBox1'). You can select acomponent to change its name and other properties. The name is importantbecause when you begin programming the behavior of the app, you'll needto refer to particular components by name.

The component designer is used only to specify the way the application willlook (it's presentation). If you download the app we've developed thus far, itwill look fine but nothing will happen when the user types text and clicks onthe "Speak It" button.

Programming the App's Behavior

You can click on the Open Blocks Editor button in the Designer menu tobegin programming the behavior of the application. If you were writing atraditional computer program, you would type code using a programminglanguage like Python or Java at this point. With App Inventor, you programthe app's behavior by configuring pre-defined blocks.

The Blocks Editor provides you with two palettes from which you can dragblocks, the Built-in pallete and the "My Blocks" palette. The Built-In palette:

provides general programming blocks you'll need to specify the behavior andlogic of the app. We'll explore these later.

The My Blocks palette:

Page 9: App Inventor ch1-4 - USF Computer Sciencewolber/bookChapters/App_Inventor_ch1_4.pdf · Chapter 2: Building And Deploying an App with App Inventor This chapter describes App Inventor

has blocks representing the components of your particular application, theones that were added in the Component Designer. Our example has threecomponents: TextBox1, SpeakItButton, and TextToSpeech1. Each of thesecomponents has a drawer containing function and property blocks for thecomponent. As you can see, there is also a My Definitions component forcustom variables and functions you define.

When you click on a component, say the SpeakItButton, you can see all ofthe events and operations associated with it:

Each component's drawer contains blocks associated with the component, including events,properties, and functions that can be applied to it.

The pink blocks at the top represent events that can occur which are related to thecomponent. As the snapshot shows, a button component like SpeakItButton has fourassociated events: when the user clicks it, when the user touches it or in some other

Page 10: App Inventor ch1-4 - USF Computer Sciencewolber/bookChapters/App_Inventor_ch1_4.pdf · Chapter 2: Building And Deploying an App with App Inventor This chapter describes App Inventor

manner gives it focus (Got Focus), when it loses focus (LostFocus) and when it is initialized(on app startup).

For our simple 'type in some words and click to speak them' example, we'll first choose theSpeakItButton.Click event and drag it into the program block area:

This event block is a "when do" block and can be read as "when the user clicks onSpeakItButton, do ..." Until we drag in some operations within this event block, nothing willhappen when the app runs and the user clicks the button.

In this case, the application should respond to the click by getting the text the end-user hasentered and giving it to the TextToSpeech component. So we first click on theTextToSpeech1 component's drawer to see all of its operations. It has a number of them,but the one we want is "Speak" as we want to tell the "little man" to say something:

The something we want him to say, the message, is the contents of TextBox1. That is, wemust envision that the user has typed in some words in the text box and then clicked on theSpeakIt button.

We can get what the user has typed by opening the TextBox1 drawer and finding its "Text"property. This "Text" property is a memory cell within the TextBox1 component whose job isto watch what the user types. With this property, we can build our behavior:

TextBox1.Text -- what the user has typed -- is hooked in as the "message" of the functionTextToSpeech1.Speak. Both of these blocks are placed within the SpeakItButton.Click block.

In programming, we call such a when-do block, along with the operations inside it, anevent-handler. In this sample, the event handler has only one operation (block), but itcan have many.

The event-handler reads as "When SpeakItButton is clicked, TextToSpeech1

Page 11: App Inventor ch1-4 - USF Computer Sciencewolber/bookChapters/App_Inventor_ch1_4.pdf · Chapter 2: Building And Deploying an App with App Inventor This chapter describes App Inventor

should speak the message that is the text entered by the end-user inTextBox1.

Download the App to Your Phone

When you finish programming the blocks of an app, you can test it out onyour phone. One of the coolest features of App Inventor is that you candownload an app to your phone by scanning a barcode.

Back in the Component Designer, select Package For Phone | Show Barcode:

After a minute, a barcode will appear on the screen:

You'll need a barcode scanner on your phone-- you can download one from ZXing if youdon't have one. Once you have it, start it up and place the barcode scanner's window sothat the barcode on your computer appears within it. When the phone reads the barcode, itwill step you through downloading and installing your app to the phone.

When you run the application, it will look like this:

Page 12: App Inventor ch1-4 - USF Computer Sciencewolber/bookChapters/App_Inventor_ch1_4.pdf · Chapter 2: Building And Deploying an App with App Inventor This chapter describes App Inventor

When you, the end-user, enter words and press "Speak It", the words will bespoken.

Test the App in the Emulator

Android provides an emulator so you can test apps on your computerwithout downloading to an actual phone. Copying the app for use on theemulator is faster than downloading the app to a phone, so using theemulator can speed the development process. It also allows you to testwhen you don't have an Android phone handy.

Of course the emulator doesn't really make calls or texts, nor does it receivethem. It also doesn't move or turn, so it can't be used to test apps thatrespond to sensor events. But for most apps, the emulator can help you testmost of its behaviors.

Installing and Running the Emulator

The emulator is part of the Android Software Development Kit (SDK). TheSDK has a bunch of code and tools for developing Android apps with Java.We won't be programming in Java, but we'll use the same emulator thatJavaites use to test their apps.

Page 13: App Inventor ch1-4 - USF Computer Sciencewolber/bookChapters/App_Inventor_ch1_4.pdf · Chapter 2: Building And Deploying an App with App Inventor This chapter describes App Inventor

You can install the SDK (and the emulator) on your computer using theinstructions below. For additional help, see the documentation at:http://developer.android.com/guide

1. Download the android SDK on to your computer. If you are on a USFcomputer science computer, its already there! If not, get it and make sureyour path is setup correctly.

2. Create an android virtual device (AVD). An AVD is an emulatorinstance for a particular version of the phone (e.g., version 1.5).

Enter the commands below in the terminal (the > just represents theprompt, do not type it):

> android list targets

This will show you a numbered list of the 'targets' phone versions that comeas part of your SDK. When this book "went to press" Android version 1.5came as target #2.

> android create avd -n basic -t 2

This creates an AVD named 'basic'. The "2" corresponds to the targetnumber.

You only need to do the above commands once, to create your virtualdevice.

3. Start the emulator:

> emulator -avd basic

'basic' refers to the name you gave to the AVD you created.

4. Download an app to the emulator:

a. In the App Inventor Component Designer window, open an app, andchoose Package for Phone | Download to Computer

In the App Inventor environment, there are two ways to create an apponce you've coded its blocks, and both appear under the "Package forPhone" menu. The first choice is "Show Barcode" which will create theapp and display a barcode for it. You can then use a barcode scanner todownload the app on the phone.

Page 14: App Inventor ch1-4 - USF Computer Sciencewolber/bookChapters/App_Inventor_ch1_4.pdf · Chapter 2: Building And Deploying an App with App Inventor This chapter describes App Inventor

The second choice is "Download to your computer". If you want to testyour app with the emulator, choose this option and download the app toyour computer. This will create a file with the extension .apk (anandroid package) on your hard disk.

b. Open a different terminal window than the one that started the emulatorand run the install command. For instance, if your downloaded app is namedPurr.apk and is stored in your "Download" folder, use the followingcommand:

> adb install -r Download/Purr.apk

c. Be careful the second time you download the same app-- it will be given adifferent name such as Purr(2).apk. You'll need to rename it on yourcomputer to "Purr2.apk" before installing it on the emulator, as the "install"command doesn't allow parenthesis in the file names.

Page 15: App Inventor ch1-4 - USF Computer Sciencewolber/bookChapters/App_Inventor_ch1_4.pdf · Chapter 2: Building And Deploying an App with App Inventor This chapter describes App Inventor

Chapter 3: An App Is...This chapter is conceptual: we examine the structure of an app, beginningwith the analogy that an app is like a recipe. You will learn about event-handlers, conditionals, and repeat loops, and be ready to delve into somemore complicated Android programming.

A App is a Recipe

The simplest apps are like recipes: the app specifies the computerinstructions that should be performed: do A then B then C:

An App is a Set of Event-Handlers

Most apps don't really fit the recipe paradigm, as most have graphical userinterfaces (GUIs) with which the user interacts. Such apps are betterdescribed as a set of event-handlers, with recipes that are only performed inresponse to some event.

Page 16: App Inventor ch1-4 - USF Computer Sciencewolber/bookChapters/App_Inventor_ch1_4.pdf · Chapter 2: Building And Deploying an App with App Inventor This chapter describes App Inventor

Events are often user initiated: the user clicking a button or choosing anitem from a drop-down list. The "recipe" performed in response can be oneor more of the functions that the computer or phone is capable ofperforming. We call the event and the functions executed in response to itan event-handler.

Most apps will have many event-handlers: In Chapter 2, we described anapplication which could be described with a single event-handler:

The app responded only to the SpeakItbutton.Click event, and it respondedby getting the text from the component TextBox1 (the text the user hadentered) and calling the TextToSpeech.Speak function with that text.

App Inventor is a language based on the event-handler paradigm.Conceptually, nothing happens except in response to an event. You'll neverdrag in function blocks into the app area without hooking them into anevent's "when-do" block. For instance, you wouldn't want blocks like:

floating in the block editor outside of an event-handler.

Okay, you're saying, I get the event-handler paradigm, but aren't thereactions that should be performed when an app runs, without waiting for anevent?

The answer is yes. For instance, a Twitter client for Android might need tocontact the Twitter web service to get the user's information as soon as theapp begins. With App Inventor, these fit into the event-handler paradigmthrough the use of Initialization events. Every component has anInitialization event that is triggered when the component is drawn on thescreen. If you want to do X when an app starts, you can hook X onto somecomponent's Initialization event. For instance, you could have an appwelcome the user on startup:

Page 17: App Inventor ch1-4 - USF Computer Sciencewolber/bookChapters/App_Inventor_ch1_4.pdf · Chapter 2: Building And Deploying an App with App Inventor This chapter describes App Inventor

There is also a special Timer component that allows you to trigger responseswhen a certain amount of time passes. So an app with a moving object ischaracterized as an app with a timer event where the response to the eventis to move the object.

Events types include user-initiated events like button clicks, initializationevents, timer events, and external events such as the phone receiving a textor information from a web service like Twitter arriving to the phone.

The job of the app programmer, then, is to put together blocks that say howthe phone should respond to all pertinent events.

An App Consists of Event-Handlers That Can Ask Questionsand Branch

Many responses to events are not linear recipes, but contain branches and loops. The app isallowed to ask questions -- to query the data within it-- and determine its course based onthe answers. We say that such apps have conditional branches:

Here, when the event occurs, we perform operation A, then only perform B1if some condition is true. If the condition is false, we instead perform B2.Once either of the branches completes, the app proceeds back on the mainbranch (C).

Page 18: App Inventor ch1-4 - USF Computer Sciencewolber/bookChapters/App_Inventor_ch1_4.pdf · Chapter 2: Building And Deploying an App with App Inventor This chapter describes App Inventor

Conditions are questions such as "has the score reached 100?" or "did thetext I just received come from Joe". Such examples are simple; in general,you can code any complex logic with nested conditionals and variouscomparative operators.

To check conditions in App Inventor, you'll use "if-then" blocks and "if-then-else" blocks:

You can insert any type of condition in the test slot. If its true, the blocks within the then-doare executed (B1 in the previous diagram). If it is false, the blocks within the else-do areexecuted (B2 in the previous diagram).

An App Consists of Event-Handlers That Can AskQuestions, Branch, and Repeat

Besides asking questions and branching based on the answer, you can alsobranch up in a app so as to repeat some operations multiple times. Such anup-branch is called a loop and can be characterized with the followingdiagram:

The operation A is executed, then a condition is checked. If it is true, B isexecuted. Each time B is executed, the app jumps back up and checks the

Page 19: App Inventor ch1-4 - USF Computer Sciencewolber/bookChapters/App_Inventor_ch1_4.pdf · Chapter 2: Building And Deploying an App with App Inventor This chapter describes App Inventor

condition again. This loop is repeated until the condition becomes false.

App Inventor provides two "repeat" blocks, the while-do and the foreach.

With the while-do, the condition is put into the test slot, and the operationsto repeat are put in the do slot. The foreach is specifically for repeatingoperations on a list of data.

An example of an app that uses a repeat is one that texts a list of phonenumbers. The condition in such an app is "am I at the end of the list ofnumbers?" and the operation is sending the message to the current personin the list.

An App Consists of Event-Handlers That Can AskQuestions, Branch, Repeat, and Talk to Web Services

Some apps use only the information within the device they are running on,whether that device be a phone or a computer. But many apps communicatewith the outside world by sending requests to web services.

Twitter is an example of a web service that an App Inventor app can talk toYou'll write apps that communicate with Twitter both to gather data to

Page 20: App Inventor ch1-4 - USF Computer Sciencewolber/bookChapters/App_Inventor_ch1_4.pdf · Chapter 2: Building And Deploying an App with App Inventor This chapter describes App Inventor

display on the phone, and to update your Twitter status. Apps that talk tomore than one web service are called mashups, and we'll explore those aswell.

Web services like Twitter provide an application programmer interface (API),which is the protocol for how a program communicates with the service.We'll discuss web services and APIs extensively in Chapter 6.

An App Consists of Event-Handlers That Can AskQuestions, Branch, Repeat, Talk to Web Services, andRemember Things

When you use apps, you expect them to remember things for you, such asthe contacts you enter into your contact manager app. Such memory thatlives even after an app is closed is called persistent data and is stored insome type of a database:

App Inventor provides persistent memory through a special web service andcomponent called tinywebdb. We'll explore its use and build apps such as aquiz application that lets the teacher maintain the list of questions.

Summary

A programmer must view an app both from an end-user perspective andfrom the inside-out. With App Inventor, you'll design how an app looks andthen you'll design its behavior-- the set of event-handlers that lead an appto behave as you want. You'll build these event-handlers by assembling andconfiguring blocks representing events, operations, conditional branches,repeat loops, web service operations, and database operations, then testing

Page 21: App Inventor ch1-4 - USF Computer Sciencewolber/bookChapters/App_Inventor_ch1_4.pdf · Chapter 2: Building And Deploying an App with App Inventor This chapter describes App Inventor

your constructions by actually running the app on your phone. After writinga few programs, the mapping between the internal view of an app and itsphysical manifestation will become clear. When that happens, you will be aprogrammer!

Page 22: App Inventor ch1-4 - USF Computer Sciencewolber/bookChapters/App_Inventor_ch1_4.pdf · Chapter 2: Building And Deploying an App with App Inventor This chapter describes App Inventor

Chapter 4: Components,Properties, Events, and FunctionsIn this chapter, you'll learn about components and modifying theirproperties, as well as more on programming the event-handlers of anapplication. You'll begin with a simple app that just draws a circle when abutton is clicked, then progress to an app for painting pictures on yourphone.

Components

The items that appear on the phone when an app is running-- text, inputboxes, list boxes, graphics, drawing canvases, etc.-- are called components.There are also non-visible components representing things like motionsensors and the Twitter web service.

The components that you can add to an App Inventor app are organized intopalettes that run along the left side of the designer:

Page 23: App Inventor ch1-4 - USF Computer Sciencewolber/bookChapters/App_Inventor_ch1_4.pdf · Chapter 2: Building And Deploying an App with App Inventor This chapter describes App Inventor

The "Basic" palette has the most commoncomponents. Button, Label, and TextBox areprobably the most popular: the label component isfor text the user can't modify, the TextBox is usedto get input from the end-user. The Checkbox,RadioButton, and ListPicker are for allowing theuser to choose between options. The canvas andimage are used for graphical apps like paintprograms and games.

The other palettes have more application specificcomponents: Media is for playing sounds andmovies; Animation provides an image sprite; Socialprovides components for making phone calls, texts,and accessing Twitter; Sensors providecomponents for sensing location and movement ofthe phone; Screen arangement components are forbeautifying the user interface.

Page 24: App Inventor ch1-4 - USF Computer Sciencewolber/bookChapters/App_Inventor_ch1_4.pdf · Chapter 2: Building And Deploying an App with App Inventor This chapter describes App Inventor

Properties

All components have properties-- the information needed about acomponent. One property all components have is an ID, which is the nameof the component that appears in the Blocks editor when you program anapplication's behavior. Visual components also have properties such as theirwidth, height, and background image.

Page 25: App Inventor ch1-4 - USF Computer Sciencewolber/bookChapters/App_Inventor_ch1_4.pdf · Chapter 2: Building And Deploying an App with App Inventor This chapter describes App Inventor

The snapshot above shows an app with a canvas component and a buttoncomponent below it.The left-side of the designer provides a facsimile of whatwill actually appear on the phone. In the snapshot, the button component isselected in the lower left corner, so it's properties appear in the Propertieswindow.

The right-side of the designer is for editing properties. You can select acomponent, and the properties window will switch to the properties for thatcomponent. Be sure and hit return after editing any of the properties, or thechanges won't be recorded.

The Button component is of course very common. A Button component hassome properties common to many components (ID, BackgroundColor,Width, Height), but it also has properties specific to buttons-- the text thatshould appear on it, the font size and typeface of that text, and an optionalimage for the face of the button.

Another common component is the Canvas. It defines a screen sub-area onwhich the user can draw, paint, and manipulate images. It has its own set ofproperties:

The Canvas component has an ID and like most visual components aBackgroundColor, width, and height. Often, the width of a canvas will be setto "Fill parent..." which means the canvas should span the width of itsparent, which is the screen itself. A height of 400 pixels will take most of thephone's screen.

Because canvas components allow users to paint on them, they have aPaintColor property. This property specifies the color of any end-userpainting that might occur.

Page 26: App Inventor ch1-4 - USF Computer Sciencewolber/bookChapters/App_Inventor_ch1_4.pdf · Chapter 2: Building And Deploying an App with App Inventor This chapter describes App Inventor

It is important to note that component properties can be set in theComponent Designer and in the behavior editor. In the designer, you aresetting the initial value of a property-- when the app starts, the propertiesare set with these initial values. In the behavior editor, you can specifychanges to properties that should occur in response to an event. You'll dothis by adding a block to set a property within some event handler. Forexample, if you wanted to change the canvas PaintColor when a user clickeda button, you could have an event-hanlder like the following:

Events

Besides having properties that record its state, each component also has aset of events that the component can respond to. A component's events onlyappear in the Behavior editor. For instance, here is a snapshot of thecomponent Button1's events:

Page 27: App Inventor ch1-4 - USF Computer Sciencewolber/bookChapters/App_Inventor_ch1_4.pdf · Chapter 2: Building And Deploying an App with App Inventor This chapter describes App Inventor

At the top of the palette are the events associated with a Button. The mostpopular event for a Button is, of course, the Click-- you use this block tospecify what should happen when a button is clicked. In the diagram, theprogrammer has dragged a Click event block into the app area.

The Button component also has some other events to which it responds.GotFocus is triggered when the user has touched or somehow selected abutton but hasn't yet clicked. LostFocus is triggered when the user touchessomething else on the screen so that the focus is no longer on the button.

The Initialize event is common to all components. It is triggered when thecomponent is first drawn on the screen as the app loads. You'll use thisevent to specify functions that should be executed when the app loads.

User actions like a button click are the most common type of event. Butthere are other types as well:

• Timer events-- The passing of time can trigger an event.• Sensor events-- a change in phone location can trigger a location

change event. The phone has an accelerometer which triggers motionevents.

Page 28: App Inventor ch1-4 - USF Computer Sciencewolber/bookChapters/App_Inventor_ch1_4.pdf · Chapter 2: Building And Deploying an App with App Inventor This chapter describes App Inventor

• Phone events-- when a call or text come in it can trigger an event.• Communication events-- when your app requests data from a web

service, an event will be triggered when that data is received.

Functions

Besides having properties and events that it responds to, a component alsohas functions that can be applied to it. All components have functions to setand get the value of each of it's properties. Above, we showed how a setfunction could be used to set the value of the PaintColor property of acanvas.

Most components also have other functions associated with them. Forinstance, the Canvas component, besides it property set-get functions, alsohas the following: DrawCircle, DrawLine, DrawPoint, and Clear.

If, in response to a button click, you wanted to draw a circle on the canvas,you'd specify it by dragging in the DrawCircle function and placing it in theButton.Click event handler:

As you can see from the DrawCircle block, the function has three open slots labeled x, y,and r. These slots are called parameters (they're also known as arguments). Aparameter is a piece of information that the function needs to do its job. If you told a childto draw a circle on the paper, the child might ask you: where on the paper and how big?This is the information that is needed to DrawCircle, and in App Inventor the where of acircle is specified with x and y coordinates, and the size with the radius r, all measured inscreen pixels (the size of one tiny dot on the screen).

If you left the x, y, and r slots empty, your app would not work-- parameters (slots) mustbe filled in. So After dragging the DrawCircle operation onto the program area, theprogrammer must specify actual values for the parameters. Above the blocks, there is amini-palette of programming components. In this case, you would click on the one labeledMath and chooses a "123" block that represents a number. The number block can then beplaced into the slot for x with a number, say 20, entered instead of the "123". Similar blockscan then be added for y and r:

Page 29: App Inventor ch1-4 - USF Computer Sciencewolber/bookChapters/App_Inventor_ch1_4.pdf · Chapter 2: Building And Deploying an App with App Inventor This chapter describes App Inventor

The x and y coordinates are in relation to the top-left of the screen, with x larger as you goright, and y larger as you go down:

x=0,y=0 ........... x=300,y=0

x=1,y=1

.

.

.

x=300,y=300

Now since pixels are very small, there are actually hundreds of pixels running across thewidth and the height of the phone. So if you ran this app and clicked on the button, a circlewould be drawn at x=20,y=20, which is near the top-left corner:

Summary

This chapter described the basic-building blocks of an app. Apps consist ofcomponents, both visual and non-visual. Each component has propertiesthat track of the current state of the component, things such as its widthand height.

Page 30: App Inventor ch1-4 - USF Computer Sciencewolber/bookChapters/App_Inventor_ch1_4.pdf · Chapter 2: Building And Deploying an App with App Inventor This chapter describes App Inventor

Each component also has a set of events and functions associated with itsdynamic behavior. Events are user actions and other actions that thecomponent responds to, e.g., a button responds to a user clicking it.Functions are things that can happen to a component and often change itsstate. For instance, the DrawCircle function modifies the state of a canvascomponent by drawing a circle on it. DrawCircle, like most functions, hasparameters associated with it. When invoking a function on a component,the programmer must specify these parameters so that the function knowshow to do its job (e.g., how big to draw the circle).

Problems

1. Program an application that draws a circle in the center of a canvas whena button is clicked.

2. SaveAs your DrawCircle app into another app and name it CanvasFun.Modify the program so that:

• The canvas has an image as a background. You can set this in thecomponent designer.

• The user can click on a second button to draw a green circle at 40,40.Note that you'll need to set the PaintColor property of the canvas inthe Click event handlers of both buttons.

• The user can click on a third button to clear the canvas. You'll need touse the Canvas.clear block.

3. Program the PaintPot painting app from Google:http://sites.google.com/site/appinventorhelp/tutorials/paintpot