Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading