Android 悬浮小窗口关键代码

windowManager = (WindowManager) getApplicationContext().getSystemService(WINDOW_SERVICE);
mButton = new Button(this);
mButton.setText("悬浮窗");
layoutParams = new WindowManager.LayoutParams(WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, 0, 0, PixelFormat.TRANSPARENT);
layoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL | WindowManager.LayoutParams.FLAG_SHOW_WHEN_LOCKED| WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
layoutParams.gravity = Gravity.LEFT | Gravity.TOP;
layoutParams.x = 100;
layoutParams.y = 300;
windowManager.addView(mButton, layoutParams);


// 设置悬浮窗的Touch监听
mButton.setOnTouchListener(new View.OnTouchListener() {
    int lastX, lastY;
    int paramX, paramY;

    public boolean onTouch(View v, MotionEvent event) {
        switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                lastX = (int) event.getRawX();
                lastY = (int) event.getRawY();
                paramX = layoutParams.x;
                paramY = layoutParams.y;
                break;
            case MotionEvent.ACTION_MOVE:
                int dx = (int) event.getRawX() - lastX;
                int dy = (int) event.getRawY() - lastY;
                layoutParams.x = paramX + dx;
                layoutParams.y = paramY + dy;
                // 更新悬浮窗位置
                windowManager.updateViewLayout(mButton, layoutParams);
                break;
        }
        return true;
    }
});

你可能感兴趣的:(Android 悬浮小窗口关键代码)