0

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()
Alex Marshall
  • 349
  • 3
  • 8

2 Answers2

1

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!

cactustictacs
  • 17,935
  • 2
  • 14
  • 25
  • This seems to be accurate as of this writing. I'm referencing a textbook from 2019 That is instructing me to set the setGravity() function to Gravity.TOP without any effect, implying the system is overriding this setting and forcing it to the bottom anyway. – Nicolas Mage Oct 06 '21 at 22:31
1

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.

Mohak Shah
  • 518
  • 3
  • 12