實現 Android 可拖動懸浮窗的步驟如下:
下面是一個簡單的示例代碼,用于實現可拖動的懸浮窗:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="@android:color/white"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Floating Window" />
</LinearLayout>
public class FloatWindowService extends Service implements View.OnTouchListener {
private WindowManager windowManager;
private WindowManager.LayoutParams layoutParams;
private int initialX;
private int initialY;
private float initialTouchX;
private float initialTouchY;
@Override
public void onCreate() {
super.onCreate();
// 創建懸浮窗的布局參數
layoutParams = 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) getSystemService(WINDOW_SERVICE);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
// 創建懸浮窗的視圖
LinearLayout floatLayout = (LinearLayout) LayoutInflater.from(this).inflate(R.layout.float_window, null);
floatLayout.setOnTouchListener(this);
// 將懸浮窗添加到窗口中
windowManager.addView(floatLayout, layoutParams);
return super.onStartCommand(intent, flags, startId);
}
@Override
public void onDestroy() {
super.onDestroy();
// 將懸浮窗從窗口中移除
if (windowManager != null) {
windowManager.removeView(floatLayout);
}
}
@Override
public boolean onTouch(View view, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// 記錄懸浮窗的初始位置
initialX = layoutParams.x;
initialY = layoutParams.y;
initialTouchX = event.getRawX();
initialTouchY = event.getRawY();
return true;
case MotionEvent.ACTION_MOVE:
// 更新懸浮窗的位置
layoutParams.x = initialX + (int) (event.getRawX() - initialTouchX);
layoutParams.y = initialY + (int) (event.getRawY() - initialTouchY);
windowManager.updateViewLayout(view, layoutParams);
return true;
case MotionEvent.ACTION_UP:
// 手指抬起時不處理事件
return true;
}
return false;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
<service
android:name=".FloatWindowService"
android:enabled="true"
android:exported="false" />
startService(new Intent(MainActivity.this, FloatWindowService.class));
這樣就實現了一個簡單的