Search code examples
androidglanceglance-appwidget

How to have a toast show on an onClick in a Compose Glance widget?


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?


Solution

  • 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.