XML Layout Example

This example shows how to create a user interface from an XML description. In practice, the description is not written as XML, but as a Python representation of the XML normally used in Android applications. In this example, the layout is defined in the build.py script that is responsible for building a package.

A screenshot of the application.

We begin by importing the classes and modules that will be needed by the application.

from android.app import Activity
import android.os

We import a class from the special app_resources module that is created when the application is built. This allows us to refer to the application resources.

from app_resources import R

The XMLLayoutActivity is derived from the standard Activity class and represents the application. Android will create an instance of this class when the user runs it.

class XMLLayoutActivity(Activity):

    def __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. The return type and parameter types expected by the method are declared using the following decorator.

    @args(void, [android.os.Bundle])
    def onCreate(self, bundle):
        Activity.onCreate(self, bundle)

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


Finally, we simply pass a constant to the activity's setContentView method to set up the main user interface for the activity. The constant is a resource identifier that corresponds to the main layout description which is defined in the build script for this example.