Search code examples
androidandroid-dialogfragment

How to raise one DialogFragment above another?


Say I have several dialog fragments that are shown in response to messages and events that can arrive in any order. Normally, the last dialog shown will be on top. Is there a way to show a dialog fragment under an existing one, or change their z-order after they are shown?

It should be pretty rare for my app to show more than one dialog at a time, but it could happen. There is one particular dialog that should always be on top whenever it's visible.


Solution

  • A dialog creates an application sub-window. Android's window manager (WindowManagerService) automatically computes window's z-order depending on its type and stores it in WindowState's mLayer field. Internal Android classes have access to this field and change window's z-order sometimes, but this API is not exposed to Android SDK. So it seems that the only way to affect dialog's z-order is to recreate it.

    Everything I wrote above is just a result of a brief investigation of Android's source code so I may be wrong. And maybe there's some hacky way to do what you want using reflection and accessing private fields and methods. But I'm not sure it's a good idea to try and do it. In my opinion it would be better to have just a single dialog or even activity, and manage fragments within it.