Widget Example

This example is a minimal set of code for a home screen widget.

A screenshot of the widget.

See the following guides in Android's documentation for information about implementing App Widgets:

from android.appwidget import AppWidgetProvider
from android.widget import RemoteViews

from app_resources import R

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

class WidgetProvider(AppWidgetProvider):

    def __init__(self):
    
        AppWidgetProvider.__init__(self)

In the onUpdate method we obtain a RemoteViews object to access the views held by the layout shown in the widget, updating the ImageView with the R.id.image ID to show the preview image supplied.

    def onUpdate(self, context, manager, ids):
    
        views = RemoteViews(context.getPackageName(), R.layout.main)
        views.setImageViewResource(R.id.image, R.drawable.preview)

        for app_widget_id in ids:
            manager.updateAppWidget(app_widget_id, views)

We iterate over the widget IDs that are sent to the application via an intent, updating each widget with the updated views.

Files