Documentos de Académico
Documentos de Profesional
Documentos de Cultura
APPING-MASTERS-2013-VERDIER
Android: Session 4
PowerOfTwo
In this exercise, well display the first 200 power-of-two numbers in a list and well display a detailed view
of the formula in another activity.
PAGE 1 OF 6
ANDROID: SESSION-4
APPING-MASTERS-2013-VERDIER
We are also going to tweak the The MainActivity class. Instead of being a regular Activity, we are going
to subclass ListActivity.
public class MainActivity extends ListActivity
When the only widget in the activity is a ListView, its easier to use a ListActivity (especially if you want
to bind an existing array of data to your list, directly in the XML).
If you want to display a TextView on top of your list, youll have to switch back to a regular Activity.
You need to give an id to the widget you want to display data into. In our case, we need to display the
number on the TextView on the left and the result of the power on the right TextView, so use the
number id and the powerResult id.
PAGE 2 OF 6
ANDROID: SESSION-4
APPING-MASTERS-2013-VERDIER
The from array contains tags that are going to be referenced in the data that we use to display our
power-of-two ListView.
The to array contains widget ids that are linked to the tags declared in the from.
The ListView uses the fillMaps list of data to know what to display inside the rows. Each entry in the
list contains the data for one row in the ListView. The data for a row is made of a map containing all the
value to display linked to a tag previously declared in our from array.
Next we create an adapter to link all those previously declared data to a layout.
The last step is to set our ListView to use this adapter.
Launch your application. It should display a list containing only the number on the left.
Modify the code to display the result inside the right TextView.
PAGE 3 OF 6
ANDROID: SESSION-4
APPING-MASTERS-2013-VERDIER
To add a new activity to your application, in AndroidManifest.xml file add the following code inside the
application node:
<activity android:name="PowerDetailActivity"></activity>
PAGE 4 OF 6
ANDROID: SESSION-4
APPING-MASTERS-2013-VERDIER
You can now finish the application and display the number and its power of two.
Step 7: Factoring
To make of application more generic we want to be able to display a list x power y (instead of only x
power 2).
Create a PowerOf class with the following fields:
number
exponent
result
PAGE 5 OF 6
ANDROID: SESSION-4
APPING-MASTERS-2013-VERDIER
Now that your list is able to display your data, you need to modify your PowerDetailActivity to support
the power of n.
PAGE 6 OF 6