Icons Example

This example shows how to access images that are included within an application's package and display them as icons.

A screenshot of the application.

We import the classes and modules needed by our application. The most relevant class to this example is the ImageView class.

from android.app import Activity
import android.os
from android.widget import GridLayout, ImageView

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 IconsActivity 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 IconsActivity(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(10)

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 < 15:
        
            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
        
        self.setContentView(layout)

Finally, we make the layout the main view in the activity so that its contents are shown.

Files