View Switcher Example

This example shows how to switch between two views.

A screenshot of the application.

We import the classes and modules that will be needed by the application. The most relevant is the ViewSwitcher classes from the android.widget module.

from import Activity
from android.view import View
from android.widget import ImageView, TextView, ViewSwitcher

from app_resources import R

The ViewActivity is derived from the standard Activity class and represents the application. Android will create an instance of this class when the user runs it, and the activity will present a graphical interface to the user.

class ViewSwitcherActivity(Activity):

The class declares that it implements the View.OnClickListener interface by including it the __interfaces__ attribute. This requires that we implement the onClick method.

    __interfaces__ = [View.OnClickListener]

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.

    def __init__(self):

The onCreate method is called when the activity is created by Android.

    def onCreate(self, bundle):

As with the init method, we must call the corresponding method in the base class.

        Activity.onCreate(self, bundle)

The user interface is an instance of the ViewSwitcher class. As with other standard views, we pass the activity instance as an argument to the class when we create it. We also create two views to display in the switcher.

        self.switcher = ViewSwitcher(self)
        textView = TextView(self)
        textView.setText("Hello world!\nClick me to show the other view.")
        imageView = ImageView(self)

We set the switcher as the main view in the activity.


The onClick method is called when the user clicks on the ViewSwitcher. It simply calls the switcher's showNext method to switch between the two views.

    def onClick(self, view):