Forum Discussion

EvgenyZobnin's avatar
EvgenyZobnin
Copper Contributor
Apr 25, 2022

Dialogs and toasts in spanned mode

Hi. When the application is expanded to both screens, dialogs and toast are always displayed on the right screen. Is there anything I can do to change this behavior?

5 Replies

  • Hi Evgeny,
    thanks for your question!

    Currently there is not a way to show a Toast on a specific screen. Before Android 11, this was possible by setting its gravity to left, right or center. But as the docs say, starting Android 11 onwards gravity is just a no-op: https://developer.android.com/reference/android/widget/Toast#setGravity(int,%20int,%20int)

    For dialogs the approach is the same, changing its window's gravity associated field. You can set the dialog to the left or to the right (by default). As you can imagine, having the folding feature in the middle, it doesn't make sense to have the dialog showing up in just there in the middle of both screens.

    How can we align the dialog then?
    ```
    private fun showDialog(side: Side) {
    val builder = AlertDialog.Builder(this)
    builder.setTitle("Hello world!").setMessage("Side ${side.name} !!")

    val dialog = builder.create()
    val window = dialog.window
    window?.let {
    val wlp: WindowManager.LayoutParams = it.attributes
    wlp.gravity = when (side) {
    Side.LEFT -> Gravity.LEFT
    Side.RIGHT -> Gravity.RIGHT
    else -> Gravity.CENTER
    }
    window.attributes = wlp
    }
    dialog.show()
    }
    ```
    Being `Side` an enum we have created previously:
    `private enum class Side { LEFT, RIGHT, CENTER }`

    Note that CENTER won't place the dialg in the middle of the screen but in the middle of the right screen. RIGHT will align the dialog more to the right of the right screen.

    You can find a full sample that I've created here: https://github.com/CesarValiente/dialogs-sample (it includes as well a sample with a ContextMenu).

    Please, let me know how it went.

    Thanks,
    Cesar
    • EvgenyZobnin's avatar
      EvgenyZobnin
      Copper Contributor

      CesarValienteThank you for your quick and complete response. I solved the problem with the dialogues. For toasts I will use a third party library that allows me to change the location of the message.

Resources