This example shows how to display a grid of icons in a scrolling view.
We import the classes and modules that will be needed by the application. The most relevant are the classes from the android.widget module.
from android.app import Activity import android.os from android.widget import GridLayout, ImageView, ScrollView
We also import the R object from the special app_resources module that is created by the build script. This provides constants that we use to refer to resources bundled in the application's package.
from app_resources import R
The ScrollIconsActivity class 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 initialisation method simply calls the corresponding method in the base class.
class ScrollIconsActivity(Activity): def __init__(self): Activity.__init__(self)
The onCreate method is called when the activity is created. We call the onCreate method of the base class with the Bundle object passed to this method to set up the application.
@args(void, [android.os.Bundle]) def onCreate(self, bundle): Activity.onCreate(self, bundle)
We create a grid layout to display the icons with arbitrary numbers of rows and columns.
layout = GridLayout(self) layout.setColumnCount(6) layout.setRowCount(20)
In a loop we add each of the icons stored in the application's package, creating an ImageView to hold each of them. Each image is referred to using a constant that we obtain from the R object that we imported earlier. Each view is then added to the layout.
i = 0 while i < 30: view = ImageView(self) view.setImageResource(R.drawable.triangle) layout.addView(view) view = ImageView(self) view.setImageResource(R.drawable.square) layout.addView(view) view = ImageView(self) view.setImageResource(R.drawable.circle) layout.addView(view) view = ImageView(self) view.setImageResource(R.drawable.star) layout.addView(view) i += 1
Unlike in the Icons example, the layout is placed in a ScrollView to allow the user to access parts of the content that lie outside the visible part of the activity's window.
scrollView = ScrollView(self) scrollView.addView(layout) self.setContentView(scrollView)
Finally, we make the ScrollView the main view in the activity so that its contents are shown.