Alex Marshall
Alex Marshall

Reputation: 449

How to Create a Toast at top of Screen In Android API 30+

I'm new to Android development and am trying to create a simple notification that tells a user when some user action has been completed.

I want the notification to appear at the top of the screen and disappear on its own shortly after. Basically I want a toast.

However in Android 30+, the Toast.makeText() method doesn't allow the option to set the position of the toast and when I create a custom toast I get a warning that setting the view is deprecated.

The answer to this post recommends using a snackbar, but I can't find an elegant way to set the snackbar to appear at the top of the screen either.

What is the best way to achieve what I'm looking for?

Here's the deprecated code attempt at getting the toast to the top of the screen

       val inflater = layoutInflater
        val layout: View = inflater.inflate(
            R.layout.custom_toast, null
        )
        val text: TextView = layout.findViewById(R.id.text)
        text.text = "Hello! This is a custom toast!"

        val toast = Toast(applicationContext)
        toast.setGravity(Gravity.TOP, 0, 0)
        toast.duration = Toast.LENGTH_LONG
        toast.view = layout
        toast.show()

Upvotes: 1

Views: 3422

Answers (2)

Mohak Shah
Mohak Shah

Reputation: 572

It is not possible to set the gravity of toast in android 11 because this method is deprecated in API 30+, click here to find more information.

Upvotes: 2

cactustictacs
cactustictacs

Reputation: 19524

If you're using the Material Components library, there's a setAnchorView method on its Snackbar implementation that basically lets you specify a view that the snackbar should be above. So if there's a suitable one in your layout (or you can add one, say a Guideline in the appropriate spot) you could use that.

More info here: https://stackoverflow.com/a/58665768/13598222

I don't think Toasts are an option anymore, seems like that's a system feature now, and you don't get any control over how it renders them - you give it text, and that's it. No gravity, no custom views etc, no putting your own spin on it!

Upvotes: 2

Related Questions