Building a Compose Widget Using Jetpack Glance | by Matthew Meehan | Dec, 2021

Stay hydrated

Matthew Meehan
Photo by Manki Kim on Unsplash
Water Widget

To begin creating the app widget, some preliminary steps will need to be performed.

Glance and Compose Dependencies
Enabling Compose
Including the Snapshots Repository

Prior to writing any composables, the widget must be declared in the android manifest with additional defining information.

Widget Info

Glance widgets, just like non-composable widgets, require an xml definition for their attributes.

Widget Information
  • Its minimum sizing information in DP
  • How the widget can be resized by the user
  • The default size of the widget, which is new in Android 12, this is automatically set as 2×2 but can be scaled from 2×1 to 4×3
  • The category, which defines the type of widget; this can be Home Screen, KeyGuard, or Search Box
Widget Resizing in Android 12 Demo

Android Manifest

To properly declare the widget, a receiver will need to be written in the Android Manifest.

Water Widget and Receiver
Manifest Receiver for Water Widget
  • The intent filter is declared to receive updates to the widget
  • The metadata will use the previously defined attributes in water_widget_info.xml

Initial and Preview Layout

As a final step to this initial process, an initial and preview layout will need to be defined in order for the widget to function properly.

  • LinearLayout
  • RelativeLayout
  • GridLayout
Initial layout
Preview Layout
Preview and Initial Layouts added to Widget Information

With all of this in place, it’s time to write some composables for the widget. The widget itself is simple, it will contain four major components:

  • Text showing the daily recommended number of glasses
  • A button for adding a glass to the counter
  • A button for resetting the counter

Writing Composable Content

A separate file can be created called WaterWidgetContent.ktwhich is where the composable functions will reside.

Water Widget Counter
Water Widget Goal
Recommended Daily Glasses
Plus Vector Asset
Garbage Vector Asset
Widget Button Layout

ActionCallbacks

The Glance ActionCallbacks are exactly what they imply; they perform an action when notified.

ActionCallbacks
Buttons with Clickable Modifiers

Using State in Glance

For the widget to properly keep track of how many times the user has incremented the counter, it will need to keep track of a state; this can be done with components provided by Glance.

Add Water Logic
Constants for WaterWidget
Clear Water Logic

Putting it all together

In WaterWidgetContent.kt A composable function can be created to encapsulate each of the individual components of the widget, as well as expose the context and the state to each of them.

Water Widget Content
Widget including Content
Adding the Widget to Home Screen

Leave a Comment