Dynamically creating widgets

Up to this point we've only used the layout XML file to populate our screen. In some cases, this is just not enough. In this simple example, we want the user to have a list of buttons that they can touch to answer the questions posed to them. We could pre-create some buttons and name them button1, button2, and so on, but that means limiting the number of possible answers.

In order to create buttons from our<string-array> resources, we need to do it in Java. We created a ViewGroup earlier (in the form of the LinearLayout that we named answers). This is where we will add our dynamically created buttons.

Get Android User Interface Development now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.