android侧边悬浮
时间: 2023-10-06 22:14:09 浏览: 160
在 Android 中实现侧边悬浮窗需要使用 WindowManager 和 View 来实现。首先,需要在应用的 AndroidManifest.xml 文件中声明 SYSTEM_ALERT_WINDOW 权限,以允许应用在其他应用的上层显示窗口。
接下来,在应用中创建一个悬浮窗口的 View,并且将其添加到 WindowManager 中。可以使用 WindowManager.LayoutParams 来设置悬浮窗口的位置、大小、透明度等属性。
同时,需要添加悬浮窗口的触摸事件,以便用户可以通过拖动悬浮窗口来移动它的位置。
最后,需要在应用退出时及时移除悬浮窗口,以避免在后台运行时占用系统资源。
以下是一个简单的示例代码,可以在应用中创建一个侧边悬浮窗口:
```java
public class FloatingViewService extends Service implements View.OnTouchListener {
private WindowManager mWindowManager;
private View mFloatingView;
private int mInitialX;
private int mInitialY;
private float mInitialTouchX;
private float mInitialTouchY;
public FloatingViewService() {
// Empty constructor required for service.
}
@Override
public IBinder onBind(Intent intent) {
// Not used
return null;
}
@Override
public void onCreate() {
super.onCreate();
// Create a new view for the floating window
mFloatingView = LayoutInflater.from(this).inflate(R.layout.floating_view, null);
// Set the touch listener on the floating view
mFloatingView.setOnTouchListener(this);
// Add the floating view to the window manager
mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
WindowManager.LayoutParams layoutParams = new WindowManager.LayoutParams(
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.WRAP_CONTENT,
WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY,
WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE,
PixelFormat.TRANSLUCENT);
layoutParams.gravity = Gravity.CENTER | Gravity.START;
layoutParams.x = 0;
layoutParams.y = 0;
mWindowManager.addView(mFloatingView, layoutParams);
}
@Override
public void onDestroy() {
super.onDestroy();
// Remove the floating view from the window manager when the service is destroyed
if (mFloatingView != null) {
mWindowManager.removeView(mFloatingView);
}
}
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// Save the initial touch position and floating view position
mInitialX = layoutParams.x;
mInitialY = layoutParams.y;
mInitialTouchX = event.getRawX();
mInitialTouchY = event.getRawY();
return true;
case MotionEvent.ACTION_UP:
// Do nothing on touch up
return true;
case MotionEvent.ACTION_MOVE:
// Calculate the new position of the floating view based on the touch position
layoutParams.x = mInitialX + (int) (event.getRawX() - mInitialTouchX);
layoutParams.y = mInitialY + (int) (event.getRawY() - mInitialTouchY);
mWindowManager.updateViewLayout(mFloatingView, layoutParams);
return true;
}
return false;
}
}
```
需要注意的是,在 Android 8.0 及以上版本中,需要使用 TYPE_APPLICATION_OVERLAY 来显示悬浮窗口。而在 Android 6.0 及以上版本中,需要动态请求 SYSTEM_ALERT_WINDOW 权限。
阅读全文