APP INVENTOR TUTORIAL

EXAMPLE 4: TOGGLING IMAGES

This tutorial will show how to create toggling images. It is a clear example of how loop and booleans are used in coding.

DESIGN SECTION

First of all, we need to add all the elements to create the app layout:

  1. Drag a VerticalArrangement and select “fill parent” for both height and width. We have selected the vertical one because we want to display a central image and, just beneath, a button. Set alignHorizontal and alignVertical to “center” so that all the objects added to the arrangement will be displayed in the centre
  2. Drag a Button and change its text to “Change image”
  3. Now add two Images and upload a file for each image in the section “Picture”.
  4. The important thing is now to select the option “Visible” for only one of the two images so that the other one will be invisible. As a matter of fact, we want to switch from one image to the other by clicking the button. Let’s make Image1 visible by ticking the option.

BLOCKS SECTION

1. First of all, let’s add the code for the button. Every time the user clicks the button, something will happen, which means we are going to add a loop. A loop is a statement that allows the code to be executed repeatedly. Add the following block you find in the Button section:

when Button1.click
do 

2. Now, we have to add the code so that “if Image.2 is visible, then something will happen, otherwise something else will happen…”. Click on the Control section and add the “if then” block inside the Button block. Click on the setting icon and attach the “else” part to the if clause. 

3. Let’s create now the condition that must be checked every time the users clicks the button. We are going to say that if Image2 is visible, then Image1 has to become visible and Image2 invisible. To do that, we use booleans, that is values that can be either true or false.

Add the condition to the if clause by clicking on Image2 and drag:

Image2.visible 

Then we have to add what happens if this condition is true. Go to image2 and drag the following block:

set Image2.visible to

Then click on Logic and add “false” to the “set visible statement”. Now you just need to copy and paste the whole “set statement” and attach it to the first one. Change Image2 to image1 and false to true. 

4. But what if Image2 is not visible at the beginning? We have to add a statement to the “else” clause. Just copy and paste again the two “set visible statements” and change Image1 to Image2 and vice-versa. 

Now, run your app with Emulator! You will see your images toggling every time you press the button!

You can download the project here.