Pieces of the App Widget
In some respects, setting up an app widget is like setting up an activity:
- You usually need a layout resource
- You need a manifest entry
- You need a Java or Kotlin class
The details, though, are substantially different between activities and app widgets.
The Layout
You will need a layout resource for your app widget. In principle, this works the same as any other layout resource.
However, you have a very limited palette of available widgets and containers to choose from:
AdapterViewFlipperButtonChronometerFrameLayoutImageButtonImageViewGridLayoutGridViewLinearLayoutListViewProgressBarRelativeLayoutStackViewTextViewViewFlipper
Of those, Button, FrameLayout, ImageView, ProgressBar, and TextView are still popular today. Most of the rest are either unpopular (ImageButton, StackView) or are largely replaced (e.g., RecyclerView replacing ListView and GridView). However, you may find yourself using some of those less-popular options, simply because you cannot use things like RecyclerView and ConstraintLayout in an app widget.
The AppWidgetProvider
Instead of an Activity subclass, you will create an AppWidgetProvider subclass. AppWidgetProvider in turn extends BroadcastReceiver.
While there are a variety of methods that you could implement, the big one will be onUpdate(). This will be called when the OS proactively wants an updated copy of the UI for the app widget.
The Metadata
An app widget also needs a resource that serves in the role of metadata, describing various aspects of the app widget’s behavior. For example, you can provide details about the initial size of the app widget, or supply a preview image to show in the app widget selector UI.
While this resource is an XML file, it is not a layout, menu, or other “major” type of resource. Instead, it will go in a res/xml/ directory of your source set — this is used for arbitrary XML documents. We will see it again later in the book when we look at the preference system.
The Manifest Entry
There are a couple of ways to tell Android about a BroadcastReceiver. The approach used for app widgets is to have a <receiver> element in the manifest, much like how we have an <activity> element for our activities. So, the app widget will need a <receiver> pointing to the AppWidgetProvider subclass.
In addition, this <receiver> element will have a child XML element that tells Android about that metadata XML resource. This is a bit reminiscent of how our launcher activity has a child <intent-filter> element, just with a different syntax and role.
Prev Table of Contents Next
This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.