This example shows how to create a user interface from an XML description using references to access user interface elements. 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.
We begin by importing the classes and modules that will be needed by the application.
from android.app import Activity
from android.view import View
from android.widget import Button, LinearLayout, TextView
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 XMLLayoutRefsActivity is derived from the standard Activity class and represents the application. Android will create an instance of this class when the user runs it. The class declares that it implements an interface that we use to respond to clicks on a view.
class XMLLayoutRefsActivity(Activity):
__interfaces__ = [View.OnClickListener]
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. The return type and parameter types expected by the method are declared using the following decorator.
def onCreate(self, bundle):
Activity.onCreate(self, bundle)
As with the __init__
method, we must call the corresponding method
in the base class. We set up the activity's GUI using a resource ID.
self.setContentView(R.layout.main)
We retrieve the layout used, casting it to the correct type, then call its methods to add a button to the GUI.
layout = CAST(self.findViewById(R.id.main_layout), LinearLayout)
button = Button(self)
button.setText("Change labels")
button.setOnClickListener(self)
layout.addView(button)
We register the activity as a listener for the button and implement the following method to respond to clicks.
def onClick(self, view):
greetingLabel = CAST(self.findViewById(R.id.greeting), TextView)
signoffLabel = CAST(self.findViewById(R.id.signoff), TextView)
greetingLabel.setText("Hi there!")
signoffLabel.setText("Bye bye!")
We find views by their resource IDs in the layout and cast them to the appropriate type before calling methods to change their contents.