Friday, March 4, 2011

Android App Inventor - Lists

This post will explain the use of lists and list controls in Android App Inventor.

There are three parts to this post. In the first part I will examine how to create a list and add items to the list via the GUI, the second part will show how to make use of items in a list directly and thirdly I will show how to link a list to a GUI list control to select and display items.

To create a list we go to the Block Editor and define a new variable called 'list'. We can then call a 'make a list' method which will create a blank list.





In the GUI add a textbox and button. The textbox will be where you add the value you want added to the list. The button will call the btnAddText.Click event to add the text in the textbox to the list.

The code will also update the label underneath the button to show the current number of items in the list.

The next step is to make use of this list. In the screenshot below I have added a button and a label to the screen.  The label is not visible as it is empty at the moment.

When the button is selected on-screen the btnRandom.Click event is called. This event will randomly select one of the list items and display it in the label. The call to the random function is surrounded by an IF block to ensure that the list is not empty.

Finally, the last thing to do is associate this list with an on-screen control that we can access to select items.

On the GUI a ListPicker control has been added. We also add a Label to show the returned value.

This control will display a list of values and when the user selects one it will return the value back to the user. To associate a List with a ListPicker control we call pass the list into the ListPicker.Elements method.

In our example this is done as part of the btnAddText.Click method. This ensures that the list control is updated each time an item is added to the List.

Now that we have associated the list to the ListPicker control we can use a ListPicker.AfterPicking block to show the returned value on the Label.

The following is some screenshots showing the overall GUI design with the names of the controls.


I hope this tutorial has been helpful. Please feel free to comment if you need further information.

My other App Inventor tutorials are:
App Inventor - Simple SMS
App Inventor - Location Services

3 comments:

  1. How to make a list in main screen?
    I mean, not need to click in listpicker.

    ReplyDelete
  2. Márcio CardosoMarch 24, 2011 at 5:26 AM

    I have the same question...

    Is possible???

    ReplyDelete
  3. I have tried to work out how to do this, but cannot find a way. Maybe you can use some dynamically loaded check boxes.

    ReplyDelete