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

Keep hydrated

Picture by Manki Kim on Unsplash
Water Widget

To start creating the app widget, some preliminary steps will should be carried out.

Look and Compose Dependencies
Enabling Compose
Together with the Snapshots Repository

Previous to writing any composables, the widget should be declared within the android manifest with further defining data.

Widget Information

Look widgets, similar to non-composable widgets, require an xml definition for his or her attributes.

Widget Data
  • Its minimal sizing data in DP
  • How the widget could be resized by the person
  • The default dimension of the widget, which is new in Android 12, that is mechanically set as 2×2 however could be scaled from 2×1 to 4×3
  • The class, which defines the kind of widget; this may be House Display, KeyGuard, or Search Field
Widget Resizing in Android 12 Demo

Android Manifest

To correctly declare the widget, a receiver will should be written within the Android Manifest.

Water Widget and Receiver
Manifest Receiver for Water Widget
  • The intent filter is said to obtain updates to the widget
  • The metadata will use the beforehand outlined attributes in water_widget_info.xml

Preliminary and Preview Structure

As a closing step to this preliminary course of, an preliminary and preview structure will should be outlined to ensure that the widget to operate correctly.

  • LinearLayout
  • RelativeLayout
  • GridLayout
Preliminary Structure
Preview Structure
Preview and Preliminary Layouts added to Widget Data

With all of this in place, it’s time to write down some composables for the widget. The widget itself is easy, it is going to comprise 4 main parts:

  • Textual content displaying the each day beneficial variety of glasses
  • A button for including a glass to the counter
  • A button for resetting the counter

Writing Composable Content material

A separate file could be created known as WaterWidgetContent.kt, which is the place the composable features will reside.

Water Widget Counter
Water Widget Purpose
Advisable Every day Glasses
Plus Vector Asset
Rubbish Vector Asset
Widget Button Structure

ActionCallbacks

The Look ActionCallbacks are precisely what they suggest; they carry out an motion when notified.

ActionCallbacks
Buttons with Clickable Modifiers

Utilizing State in Look

For the widget to correctly hold observe of what number of occasions the person has incremented the counter, it might want to hold observe of a state; this may be performed with parts supplied by Look.

Add Water Logic
Constants for WaterWidget
Clear Water Logic

Placing all of it Collectively

In WaterWidgetContent.kt a composable operate could be created to encapsulate every of the person parts of the widget, in addition to expose the context and the state to every of them.

Water Widget Content material
Widget together with Content material
Including the Widget to House Display

More Posts