This is a simple example to show different types of clocks.
We import the classes that will be needed by the application, including the various clock widgets from the android.widget package.
from java.lang import System from android.app import Activity from android.os import Build, Bundle from android.view import ViewGroup from android.widget import AnalogClock, Chronometer, DigitalClock, \ LinearLayout, TextClock
We define a class based on the standard Activity class. This represents the application, and will be used to present a graphical interface to the user.
class ClocksActivity(Activity): def __init__(self): Activity.__init__(self)
The initialisation method simply calls the corresponding method in the base class. This must be done even if no other code is included in the method.
The onCreate method is called when the activity is created by Android.
def onCreate(self, bundle): Activity.onCreate(self, bundle)
As with the
__init__ method, we must call the corresponding method
in the base class.
At this point it is possible to create a user interface using views and widgets. We create a vertical layout and place the clocks in it.
layout = LinearLayout(self) layout.setOrientation(LinearLayout.VERTICAL) layout.setLayoutParams(ViewGroup.LayoutParams( ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT))
We show an analog clock, and a chronometer which counts up from a base time.
analogClock = AnalogClock(self) chronometer = Chronometer(self) chronometer.start() layout.addView(analogClock) layout.addView(chronometer)
Versions of the API earlier than level 17 could use DigitalClock to display a simple, textual, digital clock. From API level 17 onwards, we use the TextClock class to show a digital clock.
if Build.VERSION.SDK_INT < 17: digitalClock = DigitalClock(self) layout.addView(digitalClock) else: textClock = TextClock(self) layout.addView(textClock)
The layout is the main content in the activity.