This example shows how to use an adapter to display an array of strings in a ListView. An alternative form of this example that uses lists instead of arrays can be found in the Examples/StringListView directory.
We begin by declaring a unique namespace for the package we are creating. This is typically based on the reversed form of a domain name and should be unique to this package.
__package__ = "com.example.listview"
We import the classes and modules needed by our application. The notable ones for this example are those from the android.widget module.
from java.lang import Object, String from android.app import Activity from android.widget import ListView
We also import an adapter class that will let us expose arrays of strings to views.
from serpentine.adapters import StringArrayAdapter
The ListViewActivity 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 ListViewActivity(Activity): s = ("This example shows how to expose an array of strings to a list view " "via an adapter, creating text views for each of the strings.")
We define a constant string that an instance of this class can access at run-time. The contents of the string will be used to populate an array.
The initialisation method simply calls the corresponding method in the base class.
def __init__(self): Activity.__init__(self)
The onCreate method is where we set up the user interface after calling the base class's onCreate method.
def onCreate(self, bundle): Activity.onCreate(self, bundle)
We create an instance of the StringArrayAdapter class, passing an array of strings to it that is created by splitting the contents of the above string where spaces occur in it.
adapter = StringArrayAdapter(self.s.split(" ")) view = ListView(self) view.setAdapter(adapter) self.setContentView(view)
The adapter is used with a ListView that we set as the main view in the activity. This displays the array of strings as a scrolling list.