1

One of the first things I like to do with any hello world app/UI is to have some sort of popup or toast.

It seems like listeners in Glance are fairly limited to a set of action types. How can display something simple like a toast onClick?

Is the only solution to start a service and Toast in the service itself?

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62
c_idle
  • 1,448
  • 4
  • 22
  • 40

1 Answers1

3

You could use the actionRunCallback and show the toast within the action by switching to the main thread.


Button(
    text = "Show toast",
    onClick = actionRunCallback<ToastAction>()
)

class ToastAction : ActionCallback {
    override suspend fun onRun(context: Context, glanceId: GlanceId, parameters: ActionParameters) {
        Handler(context.mainLooper).post { 
            Toast.makeText(context, "My toast", Toast.LENGTH_SHORT).show()
        }
    }
}

Note: Toast are limited in Android-12 and rather discourage but for a test app might be sufficient.

Marcel
  • 2,094
  • 3
  • 23
  • 37
  • Thanks! Yeah, I don't think showing a toast from most widgets is a good idea, but I'm just testing some things out. Thank you! – c_idle Dec 16 '21 at 13:44
  • I think you can also achieve this with `withContext(Dispatchers.Main)` instead of handler – sha Nov 12 '22 at 21:12