How to check if the current activity/view has a dialog in front

warunee khammak
2 min readNov 10, 2023

--

The primary objective of the blog post is to provide developers with a reliable method for checking whether a dialog is currently in the foreground, covering scenarios where the user interface might be obscured by a pop-up dialog.

Solution 1: Using onWindowFocusChanged

override fun onWindowFocusChanged(hasWindowFocus: Boolean) {
super.onWindowFocusChanged(hasWindowFocus)
val hasWindowFocus = myView.hasWindowFocus()
// TODO hasWindowFocus = false = dialogIsShowing
}

This solution can be implemented in an Activity or a Custom View to check the window focus. However, note that it might introduce delays if the user clicks rapidly or if dialog creation is faster than the device’s processing speed. To address this, consider implementing a debounce function to introduce a delay before the next processing step.

Debounce Function:

/***
* Debouncing is a way of delaying the execution of a function until
* a certain amount of time has passed since the last time it was called.
*/
fun <T> debounce(
waitMs: Long = 300L,
scope: CoroutineScope,
destinationFunction: (T) -> Unit
): (T) -> Unit {
var debounceJob: Job? = null
return { param: T ->
debounceJob?.cancel()
debounceJob = scope.launch {
delay(waitMs)
destinationFunction(param)
}
}
}

To implement this in a Custom View:

override fun onWindowFocusChanged(hasWindowFocus: Boolean) {
super.onWindowFocusChanged(hasWindowFocus)
debounceFocusChange(Unit)
}

Don’t forget to cancel the scope in onDetachedFromWindow:

override fun onDetachedFromWindow() {
super.onDetachedFromWindow()
coroutineScope.cancel()
}

Solution 2: Using ViewTreeObserver

myView.viewTreeObserver.addOnWindowFocusChangeListener(object :
ViewTreeObserver.OnWindowFocusChangeListener {

override fun onWindowFocusChanged(hasFocus: Boolean) {
// TODO hasFocus = false = dialogIsShowing
myView.viewTreeObserver.removeOnWindowFocusChangeListener(this)
}
})

This solution is not final but works well for focusing on a single view. The debounce function can also be optionally implemented, similar to Solution 1.

I hope this helps! Let me know if you have any specific points you’d like further assistance with.

A huge thank you to ChatGPT for the invaluable help in refining this blog post. Your input has greatly enhanced the clarity and quality of the content.

--

--