要實現 Android 上可拖動的懸浮窗,可以使用 WindowManager 來操控懸浮窗的位置和狀態。下面是實現的大致步驟:
<uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW" />
WindowManager.LayoutParams params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT
);
WindowManager windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
View floatView = LayoutInflater.from(this).inflate(R.layout.layout_float_view, null);
windowManager.addView(floatView, params);
floatView.setOnTouchListener(new View.OnTouchListener() {
private int x, y;
private float touchX, touchY;
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
x = params.x;
y = params.y;
touchX = event.getRawX();
touchY = event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
int moveX = (int) (event.getRawX() - touchX);
int moveY = (int) (event.getRawY() - touchY);
params.x = x + moveX;
params.y = y + moveY;
windowManager.updateViewLayout(floatView, params);
break;
case MotionEvent.ACTION_UP:
// 處理點擊事件
break;
}
return false;
}
});
@Override
public void onDestroy() {
super.onDestroy();
if (floatView != null) {
windowManager.removeView(floatView);
}
}
通過上述步驟,就可以實現一個可拖動的懸浮窗了。需要注意的是,懸浮窗是在 WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY 類型下創建的,這需要在 AndroidManifest.xml 中添加相應的權限。另外,為了方便處理拖動事件,可以在懸浮窗視圖的 onTouchListener 中實現相應的邏輯。