A (175)

(Tuis.) #1

204 CHAPTER 6: Android Screen Design: Writing to the Display Using Activity and View


we will reference this right inside of this .setText( ) method call, by using the following single line of
(somewhat elegant, in my opinion) Java logic:


nameData.setText(milkyWay.galaxyname);


What this does is to pass over the milkyWay Galaxy object galaxyName variable as a parameter,
referenced by milkyWay.galaxyName (ObjectName.VariableName), to the nameData TextView
object that is utilizing the .setText( ) method call to retrieve and set this text (String) data value. This
data value then replaces your default “Milky Way” placeholder text value, which you previously had
set in the XML UI definition via an android:text parameter, so that you would have a text value to use
to visually refine your XML UI design, prior to your Java coding.


As you can see in Figure 6-34, the milkyWay Galaxy object has error highlighting underneath it,
which you discover upon mouse-over has an error reason that says “milkyWay cannot be resolved
to a variable” (that is, Eclipse cannot “see” your milkyWay Galaxy object). The reason for this is that
the Galaxy object is currently constructed inside of the createDefaultGalaxy( ) method, highlighted in
light blue in Figure 6-34, so the object is considered to be “local” to that method. The same problem
would have existed if you had left this code inside of your onCreate( ) method as well. The solution
is to do what you did with the TextView object declarations, and cut the Galaxy constructor line of
code outside of the createDefaultGalaxy( ) method and paste it at the top of your class above
(or below) the TextView object declarations.


Figure 6-34. Use a .setText( ) method call off the nameData TextView object configuring it with galaxyName data

Free download pdf