I am creating an android application which needs to draw over other apps. For that I am using WindowManager
to draw windows over other apps. I found the following code but I cannot manage it to run with my composable function PopupWindow()
import android.content.Context
import android.graphics.PixelFormat
import android.os.Build
import android.util.Log
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.view.WindowManager
import android.content.Context.WINDOW_SERVICE
class Window(private val context: Context) {
private val mView: View
private val mParams: WindowManager.LayoutParams
private val mWindowManager: WindowManager
private val layoutInflater: LayoutInflater
init {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
mParams = WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT
)
} else {
mParams = WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_PHONE,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT
)
}
layoutInflater = context.getSystemService(Context.LAYOUT_INFLATER_SERVICE) as LayoutInflater
mView = layoutInflater.inflate(R.layout.popup_window, null)
mView.findViewById<View>(R.id.window_close).setOnClickListener { close() }
mParams.gravity = Gravity.CENTER
mWindowManager = context.getSystemService(WINDOW_SERVICE) as WindowManager
}
fun open() {
try {
if (mView.windowToken == null) {
if (mView.parent == null) {
mWindowManager.addView(mView, mParams)
}
}
} catch (e: Exception) {
Log.d("Error1", e.toString())
}
}
fun close() {
try {
(context.getSystemService(WINDOW_SERVICE) as WindowManager).removeView(mView)
mView.invalidate()
(mView.parent as? ViewGroup)?.removeAllViews()
} catch (e: Exception) {
Log.d("Error2", e.toString())
}
}
}
I tried using the following code:
mView = ComposeView(context).apply {
PopupWindow()
}
But it showed the following error:
java.lang.IllegalStateException: ViewTreeLifecycleOwner not found from androidxpose.ui.platform.ComposeView{9be6845 V.E...... ......I. 0,0-0,0}