Search code examples
androidkotlinandroid-dialogfragment

Keep DialogFragment in front of all activities(even the ones created after showing the DialogFragment )


I have a DialogFragment that is shown in some situtation and it represents a pin request to unlock access to the app.

There is a scenario in my app where i start an activity and if some conditions are met it shows the DialogFragment(Launched from a BaseActivity) asking for a pin, but in the meanwhile the Activity A starts another a Activity B, and the DialogFragment gets behind it.

The sequence of events is

1- ActivityA is started

2- DialogFragment is shown

3- ActivityA starts ActivityB, and DialogFragment gets behind.

I want to keep the DialogFragment in front of everything even it a new activity is started after the fragment appears.

companion object {
    fun newInstance(cancelable: Boolean = false): LockCodeFragment {
        val frag = PinCodeFragment()
        frag.isCancelable = cancelable
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            frag.dialog?.window?.setType(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY)
            frag.dialog?.window?.setFlags(WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY, WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY)
        } else {
            frag.dialog?.window?.setType(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT)
            frag.dialog?.window?.setFlags(WindowManager.LayoutParams.TYPE_SYSTEM_ALERT, WindowManager.LayoutParams.TYPE_SYSTEM_ALERT)
        }
        return frag
    }

I tried to set the dialog to have the type system alert or application overlay when i instanciate the fragment, but with no success.

Is there a way to keep a DiaglogFragment in front of everything?


Solution

  • As I stated in the comment, this is not possible to my knowledge, because Fragments are being managed by the FragmentManager which is unique for each Activity. I think that the best you could do is remember if that fragment is shown somewhere (using SharedPreferences or even a field in the Application subclass) and then, when the another activity starts, check that value to possibly display the dialog again.