Académique Documents
Professionnel Documents
Culture Documents
xmlns:tools="http://schemas.android.com
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<TextView
android:id="@+id/time_display_box"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:layout_centerHorizontal="true"
android:layout_marginTop="60dp"
android:text="@string/_00_30"
android:textAppearance="?
android:attr/textAppearanceLarge"/>
<Button
android:id="@+id/startbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_below="@+id/time_disp
android:layout_centerHorizontal="true"
android:layout_marginTop="41dp"
android:text="@string/start" />
</RelativeLayout>
Note the references
to @string/start and @string/__00_30 .
These values are stored
in res/values/strings.xml :
<string name="start">Start</string>
<string
name="_00_30">00:30</string>
This illustrates the standard way of
referring to Android resources. It's best
practice to use string references rather
than hard-coding strings.
You'll notice the thing that makes this a
surprisingly easy first project: the
Android API includes a
CountDownTimer that you can use. We
set up this, and the countdown display,
as private member variables.
In onCreate() we use the built-
in setContentView method to grab our
XML layout The R.foo.bar syntax is a
standard way to refer to Android XML
resources in your code, so you'll see it a
lot.
findViewById is another method you'll
use a lot; here, it grabs the display and
the Start button from the XML layout.
For the Button to work when clicked, it
needs an OnClickListener. This is an
interface, so must be subclassed. We
could create a whole new MyButton
class to do this, but this is overkill for a
single button. Instead, we do it inline,
creating a new OnClickListener and
its onClick() method. Ours simply
calls showTimer() on the number of
milliseconds we want to use (currently
hard-coded).
countdownDisplay.setText("KABOOM!"
}
}.start();
}
The CountDownTimer class does
maximum of the paintings for us, which
is quality. Just in case there may be
already a strolling timer, we start out via
cancelling it if it exists. Then we create
a brand new timer, setting the number of
milliseconds to be counted down (from
the showTimer() parameter) and the
milliseconds in keeping with rely
interval. This interval is how frequently
the onTick()callback is fired.