Android 开发:如何创建全屏透明悬浮窗,并实现触摸穿透功能?
要实现满足以上需求的悬浮窗,可以使用以下代码:
public class FloatingWindowService extends Service implements View.OnTouchListener {
private WindowManager windowManager;
private WindowManager.LayoutParams params;
private View floatingView;
private float touchX, touchY;
@Override
public void onCreate() {
super.onCreate();
windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
floatingView = LayoutInflater.from(this).inflate(R.layout.floating_window_layout, null);
params = new WindowManager.LayoutParams(
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.MATCH_PARENT,
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL |
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE |
WindowManager.LayoutParams.FLAG_LAYOUT_IN_SCREEN |
WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS,
PixelFormat.TRANSPARENT);
params.gravity = Gravity.TOP | Gravity.LEFT;
params.x = 0;
params.y = 0;
floatingView.setOnTouchListener(this);
}
@Override
public int onStartCommand(Intent intent, int flags, int startId) {
if (floatingView != null) {
windowManager.addView(floatingView, params);
}
return START_STICKY;
}
@Override
public void onDestroy() {
super.onDestroy();
if (floatingView != null) {
windowManager.removeView(floatingView);
}
}
@Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
touchX = event.getRawX();
touchY = event.getRawY();
}
return false;
}
@Nullable
@Override
public IBinder onBind(Intent intent) {
return null;
}
}
这段代码创建了一个悬浮窗的服务,通过在 onStartCommand 方法中将悬浮窗添加到 WindowManager 中。设置 WindowManager.LayoutParams 的一些属性可以实现悬浮窗的全屏透明效果,并且不影响用户操作悬浮窗下面的界面。在 onTouch 方法中记录触摸位置,返回 false 可以使触摸事件穿透悬浮窗正常操作下面的界面。
请确保在 AndroidManifest.xml 文件中添加以下权限:
<uses-permission android:name='android.permission.SYSTEM_ALERT_WINDOW' />
然后在你的 Activity 中启动悬浮窗服务:
Intent intent = new Intent(this, FloatingWindowService.class);
startService(intent);
这样就可以实现满足你需求的悬浮窗了。
原文地址: https://www.cveoy.top/t/topic/qEB6 著作权归作者所有。请勿转载和采集!