要实现 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 中实现相应的逻辑。
辰迅云「云服务器」,即开即用、新一代英特尔至强铂金CPU、三副本存储NVMe SSD云盘,价格低至29元/月。点击查看>>
推荐阅读: android webview更新的方法是什么