import android.content.Context; import android.graphics.PixelFormat; import android.view.Gravity; import android.view.View; import android.view.WindowManager; public class FloatWindow { private View view; private WindowManager windowManager; private WindowManager.LayoutParams layoutParams; //单例对象 //private static FloatWindow floatWindow; public FloatWindow(Context context, View view) { this.view = view; windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE); layoutParams = new WindowManager.LayoutParams(); layoutParams.type = WindowManager.LayoutParams.TYPE_TOAST; layoutParams.format = PixelFormat.TRANSPARENT; layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE; layoutParams.height = ScreenUtil.dp2px(200); layoutParams.width = ScreenUtil.getScreenWidth(); layoutParams.gravity = Gravity.TOP | Gravity.CENTER_HORIZONTAL; } // //单例模式, // public static FloatWindow getInstance(Context context, View view) { // if (floatWindow == null) { // synchronized (FloatService.class) { // if (floatWindow == null) // return floatWindow = new FloatWindow(context, view); // else // return floatWindow; // } // } else return floatWindow; // } //设置Flag public void setFlags(int flags) { layoutParams.flags = flags; update(); } public void updateXY(int x, int y) { layoutParams.x += x; layoutParams.y += y; update(); } public void setXY(int x, int y) { layoutParams.x = x; layoutParams.y = y; update(); } //设置宽高,传入-1.则不修改 public void setWH(int width, int height) { if (width != -1) layoutParams.width = width; if (height != -1) layoutParams.height = height; update(); } //显示 public void show() { if (!view.isShown()) { windowManager.addView(view, layoutParams); } } //移除 public void remove() { if (view.isShown()) { windowManager.removeView(view); } } //更新 public void update() { if (view.isShown()) windowManager.updateViewLayout(view, layoutParams); } }
安卓悬浮窗
最新推荐文章于 2021-05-25 18:18:54 发布