This article will guide you through the complete process of widget creation. We will do this in steps:

  1. Introduction to widgets
  2. Create a widget of 1*1 dimension: we will add the basic files to the project that is needed to create a widget.
  3. Add the click listener: we will see here that how the click listener works and how it is different from the normal click listener.
  4. Adding multiple widgets for your app: We will see how to different widgets to the widget provider.
  5. Update the Data/UI for widget: We will detect the size of the widget and then accordingly change the data/UI for the widget.
  6. Handling adapters for widget: We will see how to add Gridview/Listview/Stackview on the widget.

Sample project

I have created a sample project to guide you through this tutorial for creating the widget. you can take the pull from here.

Here i have created branches for all the steps required. I think this project is going to be sufficient to get the idea on how to create a widget in android. ok then, let's get started.


Introduction to widgets

Widget is the part of our android application, which stays outside the app. It operates in a different process than our application. These are treated as a separate app that works on homescreen. So instead of using normal Views that we use in our application, android uses Remote Views. Remote views seems just like any other xml views that we use in app creation, but with minor changes.

For example, this is the layout file for our widget, for now it just shows an image.

Although they seems similar to normal views they have some limitations on what they can support. They normally support all the popular basic views, but views like constraint layout and recycler views are not supported, to see the full list of supported views you can refer to :

Now, to access the views in java file we use findViewById(). But here we have methods like setTextViewText() to add text to the textview.

Now lets start with adding a widget to our homescreen.


Create a widget of 1*1 dimension

We are going to place a widget on the homescreen, for now it will show a icon there. This icon will be of 1*1 dimension.

Switch to branch step_1-basic_widget_creation.

At first we need to add a file at res/xml. i am calling this file sample_widget_info.xml. It consist of “appwidget-provider” which gives the basic information regarding our widget. It is as follows:

I got this image from https://developer.android.com/guide/practices/ui_guidelines/widget_design.html#anatomy .

  • According to the above image, to create a widget of 1*1 dimension we need the minWidth and minHeight of 40dp respectively.
  • initialLayout attribute decides which view to use initially when we add the widget to the homescreen.
  • preview_image attribute decides what icon/image to show in the widget selector. Here as our selection of dimension, the icon is shows as 1*1 widget.
  • resizeMode attribute defines if we want the widget to be able to expand horizontally or vertically.
  • updatePeriodMillis attribute defines when time interval to update the widget. the minimum time we can give is 30 minutes i.e. 1800000.
  • widgetCategory attribute defines where to put the widget homescreen or keyboard.

Now we have to tell android that we have added the widget for our app and we do this by defining a receiver in the manifest file. This receiver will extend AppWidgetProvider, here that file is SampleAppWidgetProvider.

We will add this receiver in the manifest file.

Here we added the action to detect:

  • An new instance of Your AppWidget added to Home Screen from AppWidget Chooser( from AppWidget provider) is added.
  • When requested update interval having lapsed which you have provided in AppWidget info file using android:updatePeriodMillis attribute.
  • When device reboot

The meta-data points to the info file we created for our widget.

Now if all has gone correctly, after installing the app, you can see the widget option in the widget provider in your mobile. just drag it on the homescreen and you can see it.


Add the click listener

Now we want to open an activity when we click on that widget. Here the click implementation is a little different than the normal click listener. We are using pending intent to open an activity here. Pending intent is used here because by this we can declare an Intent and and execute it on the click of the widget, same as we use it for notifications.

To learn more about Pending Intent go to:

Now switch to the branch step_2-widget_click_implementation.

For implement the click, we are now going to use file SampleAppWidgetProvider. Here we are only going to use onUpdate() method. This method get called whenever there is a chance that the widget gets updated (not the widgets dimensions or options, more on this later).

It provides following parameters:

  • Context : To provide us the context. gets information about installed AppWidget providers and other AppWidget related state.
  • AppWidgetManager : Gives information about installed AppWidgets providers and other AppWidget related state.
  • int[] : This is an array of appWidgetIds, these ids represents all the AppWidgets that are available on the homescreen for our app.

Now, we are going to add a for loop in onUpdate() method to access all the widgets that are available on the homescreen for our app.

Here updateAppWidget() method will handle the Remote Views work. For now we only want to open an activity nothing more. so our updateAppWidget() method will look like this:

Here we did 3 things:

  • Created a pending intent to open MainActivity.
  • Constructed a Remote View and added the click listener via the method setOnClickPendingIntent().
  • Instruct the widget to update the widget, we will call this method everytime we update the widget.

All is done, now try it yourself, now if you click on the icon in the app widget, then you can open an activity.

Ok, now lets go a step further, and we will add 2 images in the widget and we will open different activities on each click. If you have issue regarding that, switch the branch to

Switch to the branch step_2-widget_multi_click_implementation


Adding multiple widgets for your app

We added a single widget to home screen, now what if you want one widget to open an activity like we did before and another widget to show the list on homescreen. Suppose you need these 2 widgets,

Now for this you need 2 types of views.

There are two ways to do it.

  • We can use one xml file and one AppWidgetProvider and detect the change in dimension when you increase or decrease the size and refresh the view to show the new view and handle accordingly. But in this case in the Widget provider you will only see one widget with the dimension you define in the info file sample_widget_info.xml.
  • We can use 2 xml file and 2 AppWidgetProvider for these 2 widgets. The plus point here is that we will be seeing 2 widgets in the Widget Provider but here we cant change the size of the 2 widgets below the minimum dimensions we provide. Here we will try this step and we will look into the first one afterwards.

Switch to the branch step_3-multiple_widget.

Lets create a second info file white_sample_widget_info.xml, second AppWidgetProvider file SampleWhiteAppWidgetProvider.java and second layout file layout_widget_white_simple.xml. If you have any problem then refer to the code in the above mentioned branch.


Now we will implement the first method to show multiple view in single widget.

Switch to the branch step_3-multiple_view_single_widget

Here we have 2 views but one AppWidgetProvider.

Now this method is a little tricky one, as mentioned above in step 3 the onUpdate() method don't get called when you change the dimension of the widget, instead onAppWidgetOptionsChanged() methods gets called. So instead of calling the update method to get the Remote View, we are going to use a service which will notify that the view is updated and via that we w will refresh the widget. The service is going to be an Intent Service WidgetUpdateService.java.

This service is triggered from 2 places, from onUpdate() method and from onAppWidgetOptionsChanged(). Now we are going to create a Remote View object from that service, We did this because we want to detect the change in dimensions of the widget and it cant be done from onUpdate() method. So the 2 methods in our SampleAppWidgetProvider.java will look like this:

In startActionUpdateAppWidgets() method we are starting the service as

We will handle ACTION_UPDATE_APP_WIDGETS action in onHandleIntent() method. Here we are going to get an instance of AppWidgetManager and via this we are going to call the update method updateAppAllWidget() of SampleAppWidgetProvider.java class to get the Remote View. We will do this as:

And the updateAppAllWidget() now handles the updation of all the widgets on the screen(the work we were doing in onUpdate() is done here). It looks like this:

Now we want to detect the change in dimension of the widget, we do this as:

As you can see, to get the width we use the method getAppWidgetOptions(). This method can be used to any other option also. So to get the minimum width of the widget i used the code:

So we are providing the updateAppWidget() remote view according to our need. By the table I mentioned above for dimensions, I put the check of widget width less than 300 to occupy minimum of 4 blocks of homescreen. If width is less than 300, i want to show the smaller layout else the larger view of the widget.

One thing to notice, I used 300 as my mark if I want the size of the widget less than 4*1. It came from that table only, but to remember it easily I use multiple of 100. For most cases this will work.

  • width < 300 : Dimension will be 4*1.
  • width < 200 : Dimension will be 3*1.
  • width < 100 : Dimension will be 2*1.
  • Default minWidth is for 1*1.

Then we just want to implement same click listener and start the activity. Both the methods to get the remove view are as follows:

Its a lot to take in I know, You can refer to the code i provided if you have any issues, it will help you.


Update the Data/UI for widget

It will be going to be same as above with minor changes, just to make this this updating concept clear.

Switch to the branch step_4-update_view_by_height.

Suppose you want to show a text at the top of widget if the height of the widget is increased. If height of the widget is greater than 100, we will show the text.

Here we use the PendingIntent flag FLAG_UPDATE_CURRENT because we wanted to update the current state of the MainActivity.


Handling adapters for widget

These are all simple views we used to show on the widget, what if we want to show a Collection View(listview or a gridview or a stackview).StackView is the image view we see for some apps. eg. Android Authority app) All uses the same concept so i am going to use a listview here.

As normal Listview for widget, we need the adapter here, but the normal adapter will not work here, instead we are going to start a service which will trigger the adapter and handle our listview.

Switch to the branch step_5-widget_list_view.

Few things to notice here:

  • we will use setRemoteAdapter() method to attach the adapter to our ListView. You can see this in our WidgetProvider.
  • It will start the RemoteViewsService service which trigger, the RemoteViewsService.RemoteViewsFactory. Its an interface for an adapter between a remote collection view, in our case for ListView. You can see this in ListViewWidgetService.
  • We are detecting the change in the size of the widget in onAppWidgetOptionsChanged() and if width is greater than 300 we are starting the service.

In the service we are creating the data and saving it in sharedprefs. You can handle data however you want to handle. After that same process, get the instance of AppWidgetManager and call updateAllAppWidget().

Now in the adapter class AppWidgetListView. Mainly there are 2 important methods, getCount() to get the size of the list to show and getViewAt() to get the remote view of the specific position.

Now, we have to implement the click on the list item to do a task, here we are opening the activity with some data. In remoteView the click works differently on collection views. Implementing the click to each of the item is an expensive task, so we implement the click to the complete list view in the AppWidgetProvider.

Then we add the extra data for our click in the adapter we created in getViewAt. It is done by fillInIntent.

So after implementing the click, our getViewAt() method looks like this:

Now if you run the app, you can see the complete work with the click on the list item.


)

Puru Chauhan

Written by

An Android Developer from Passion to Profession. Trying each day to learn something new, to do something different...

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade