WindowManager.addView()是Android中的一个方法,用于在屏幕上添加一个窗口。它允许你在应用程序的上下文之外创建一个窗口,并将其显示在其他应用程序或系统界面上。
-
新建一个自定义View用于显示
class MyView @JvmOverloads constructor(context: Context?,attrs: AttributeSet? = null,defStyleAttr: Int = 0) :View(context, attrs, defStyleAttr) {var myImage:Bitmap?=nullvar pX = 0fvar pY = 0finit {myImage = BitmapFactory.decodeResource(resources,R.mipmap.image)}fun setPos(x:Float,y:Float){this.pX = x;this.pY = yinvalidate()}override fun onDraw(canvas: Canvas?) {super.onDraw(canvas)if (pX != 0f||pY != 0f){myImage?.let {canvas?.drawBitmap(it,pX,pY,null)}}} }
-
使用windowManager.addView()显示
var myView :MyView?=nullvar randomCount = 0private fun show() {myView = MyView(mConext)val layoutParams = WindowManager.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT,WindowManager.LayoutParams.WRAP_CONTENT,WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,// 设置窗口类型为悬浮窗口,需要悬浮窗权限WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE or WindowManager.LayoutParams.FLAG_NOT_TOUCHABLE,// 窗口不需要获取焦点PixelFormat.TRANSLUCENT // 设置窗口背景为透明)val windowManager = getSystemService(Context.WINDOW_SERVICE) as WindowManagerwindowManager.addView(myView , layoutParams)CoroutineScope(Dispatchers.IO).launch {while (randomCount < 20){delay(1000)withContext(Dispatchers.Main){myView?.let {it.setPos((0 until 500).random().toFloat(), (0 until 500).random().toFloat())}}randomCount ++}withContext(Dispatchers.Main){windowManager.removeView(myView)}}}
首先创建了一个WindowManager对象,在这个对象上进行操作。然后创建了一个自定义的MyView对象,作为要添加的窗口的内容。接下来,创建了WindowManager.LayoutParams对象,用于指定窗口的各种属性,比如宽度、高度、位置等。最后,通过windowManager.addView()方法将自定义的View添加到WindowManager中,从而将其显示在屏幕上。