I’m developing an SDK, and I need to detect when a dialog is shown within the host app, but I don’t want to rely on explicit triggers from the host app.
The host app creates a dialog like this:
private fun createAlertDialog() {
val dialog: AlertDialog
val input = EditText(this).apply {
layoutParams = LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.MATCH_PARENT
)
inputType = InputType.TYPE_TEXT_VARIATION_PASSWORD or InputType.TYPE_CLASS_TEXT
filters = arrayOf(InputFilter.LengthFilter(15))
id = R.id.edit_text_dialog
}
val ll = LinearLayout(this).apply {
orientation = LinearLayout.VERTICAL
addView(input)
}
val builder: AlertDialog.Builder = AlertDialog.Builder(this)
.setCancelable(false)
.setTitle("Dialog Title")
.setMessage("Dialog Message")
.setView(ll)
.setOnKeyListener { dialog, keyCode, event ->
if (keyCode == KeyEvent.KEYCODE_BACK) {
dialog.dismiss()
true
} else {
false
}
}
.setPositiveButton("Ok") { _, _ -> }
dialog = builder.create()
dialog.window?.setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE)
dialog.show()
dialog.getButton(DialogInterface.BUTTON_POSITIVE).id = R.id.button_dialog
}
I want to detect the dialog being shown from my SDK without the host app explicitly calling any SDK methods. I thought about using View.addOnLayoutChangeListener
on the activity’s root view. Here is what I have tried so far and it’s doesn’t work:
// Inside my SDK code
fun observeDialogShowing(activity: Activity) {
val rootView = activity.window.decorView.rootView
rootView.addOnLayoutChangeListener(object : View.OnLayoutChangeListener {
override fun onLayoutChange(
v: View?,
left: Int,
top: Int,
right: Int,
bottom: Int,
oldLeft: Int,
oldTop: Int,
oldRight: Int,
oldBottom: Int
) {
// Check if the dialog view is now visible
Log.d("MainActivity2", "onLayoutChange")
}
})
}
I tried to using the ActivityLifecycleCallbacks interface and check if a dialog is shown in the onActivityResumed method and also using the ViewTreeObserver.OnGlobalLayoutListener interface.
Both options don’t work.
My question is: How can I detect when a dialog is shown in an Android app from my SDK without requiring explicit triggers from the host app?