Widgets in android

A widget is a small gadget or control of your android application placed on the home screen. Widgets can be very handy as they allow you to put your favourite applications on your home screen in order to quickly access them. You have probably seen some common widgets, such as music widget, weather widget, clock widget e.t.c

Widgets could be of many types such as information widgets, collection widgets, control widgets and hybrid widgets. Android provides us a complete framework to develop our own widgets.

Widget - XML file

In order to create an application widget, first thing you need is AppWidgetProviderInfo object, which you will define in a separate widget XML file. In order to do that, right click on your project and create a new folder called xml. Now right click on the newly created folder and create a new XML file. The resource type of the XML file should be set to AppWidgetProvider. In the xml file, define some properties which are as follows −

<appwidget-provider 
   xmlns:android="http://schemas.android.com/apk/res/android" 
   android:minWidth="146dp" 
   android:updatePeriodMillis="0" 
   android:minHeight="146dp" 
   android:initialLayout="@layout/activity_main">
</appwidget-provider>

Widget - Layout file

Now you have to define the layout of your widget in your default XML file. You can drag components to generate auto xml.

Widget - Java file

After defining layout, now create a new JAVA file or use existing one, and extend it with AppWidgetProvider class and override its update method as follows.

In the update method, you have to define the object of two classes which are PendingIntent and RemoteViews. Its syntax is −

PendingIntent pending = PendingIntent.getActivity(context, 0, intent, 0);
RemoteViews views = new RemoteViews(context.getPackageName(), R.layout.activity_main);

In the end you have to call an update method updateAppWidget() of the AppWidgetManager class. Its syntax is −

appWidgetManager.updateAppWidget(currentWidgetId,views);