Wednesday, May 18, 2011

Android tutorial: How to make a simple widget

It's been a while since the last tutorial  But here is a new one! In this tutorial i will show you how you can make a nice simple widget that you can update by touching the screen. On the bottom of this tutorial  you will find the source code that makes this Widget work.
Here is an overview of all the files we need to make / edit.

WidgetActivity.java
In this class all the logic resides.
  • Layout file -> widget.xml
This holds the view
  • Xml file -> widgetprovider.xml
Schematic that is needed to build a Widget
  • AndroidManifest.xml
To make the Widget work we have to make changes to the Manifest

Lets get started with the first item and work to the bottom!
As i said this is the control center of our plugin! Here is where the magic happens  I will not post the entire class here because the source code is in the bottom for those that want to go deeper.

@Override
public void onUpdate( Context context, AppWidgetManager appWidgetManager, int[] appWidgetIds ){
//Save all incomming parameters
if (null == context)
context = WidgetActivity.context;
if (null == appWidgetManager)
appWidgetManager = WidgetActivity.appWidgetManager;
if (null == appWidgetIds)
appWidgetIds = WidgetActivity.appWidgetIds;
WidgetActivity.Widget = this;
WidgetActivity.context = context;
WidgetActivity.appWidgetManager = appWidgetManager;
WidgetActivity.appWidgetIds = appWidgetIds;
Log.i("PXR", "onUpdate");
final int N = appWidgetIds.length;
for (int i=0; i < N; i++) {
int appWidgetId = appWidgetIds[i];
//update the widget
updateAppWidget(context,appWidgetManager, appWidgetId);
}
}

Read more: XR