android悬浮view-FloatingView

https://github.com/marshallino16/FloatingView

转载于:https://www.cnblogs.com/wjw334/p/4380572.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Android悬浮窗(Floating Window)可以让应用在后台运行时,在屏幕上显示出一个可移动的窗口,用户可以在窗口中执行相应的操作。以下是一个简单的实现示例: 1. 在AndroidManifest.xml文件中添悬浮窗权限 ``` <uses-permission android:name="android.permission.SYSTEM_ALERT_WINDOW"/> ``` 2. 新建一个Service类,并在onCreate()方法中创建悬浮窗 ``` public class FloatingWindowService extends Service { private WindowManager windowManager; private View floatingView; @Override public void onCreate() { super.onCreate(); windowManager = (WindowManager) getSystemService(WINDOW_SERVICE); // 创建悬浮View floatingView = LayoutInflater.from(this).inflate(R.layout.floating_window, null); // 设置悬浮窗参数 WindowManager.LayoutParams params = new WindowManager.LayoutParams( WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, Build.VERSION.SDK_INT >= Build.VERSION_CODES.O ? WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY : WindowManager.LayoutParams.TYPE_PHONE, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT); // 设置悬浮窗初始位置 params.gravity = Gravity.CENTER | Gravity.START; params.x = 0; params.y = 0; // 将悬浮窗添到WindowManager windowManager.addView(floatingView, params); } @Nullable @Override public IBinder onBind(Intent intent) { return null; } @Override public void onDestroy() { super.onDestroy(); // 移除悬浮窗 if (floatingView != null) { windowManager.removeView(floatingView); } } } ``` 3. 在悬浮窗布局文件(floating_window.xml)中添需要显示的内容 ``` <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/floating_window" android:layout_width="wrap_content" android:layout_height="wrap_content" android:background="@android:color/transparent"> <!-- 添需要显示的内容 --> </RelativeLayout> ``` 4. 在Activity中启动Service ``` Intent intent = new Intent(this, FloatingWindowService.class); startService(intent); ``` 这样就可以实现一个简单的Android悬浮窗了。需要注意的是,悬浮窗权限在Android 6.0以上的系统中需要动态申请,具体实现可以参考Android官方文档。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值