基于activity 全局悬浮球代码实现
时间: 2023-10-10 18:15:45 浏览: 92
以下是一个基于 Activity 实现全局悬浮球的代码示例:
```java
public class FloatingActivity extends Activity implements View.OnTouchListener {
private WindowManager mWindowManager;
private WindowManager.LayoutParams mLayoutParams;
private ImageView mFloatingView;
private int mStartX, mStartY;
private int mLastX, mLastY;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_floating);
// 设置窗口属性
mLayoutParams = new WindowManager.LayoutParams();
mLayoutParams.type = WindowManager.LayoutParams.TYPE_APPLICATION_OVERLAY;
mLayoutParams.format = PixelFormat.RGBA_8888;
mLayoutParams.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
mLayoutParams.width = WindowManager.LayoutParams.WRAP_CONTENT;
mLayoutParams.height = WindowManager.LayoutParams.WRAP_CONTENT;
mLayoutParams.gravity = Gravity.TOP | Gravity.START;
// 添加悬浮球 View
mFloatingView = new ImageView(this);
mFloatingView.setImageResource(R.drawable.ic_floating_ball);
mFloatingView.setOnTouchListener(this);
mWindowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
mWindowManager.addView(mFloatingView, mLayoutParams);
}
@Override
public boolean onTouch(View view, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// 记录起始位置
mStartX = mLayoutParams.x;
mStartY = mLayoutParams.y;
// 记录上一次位置
mLastX = (int) event.getRawX();
mLastY = (int) event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
// 计算移动距离
int dx = (int) (event.getRawX() - mLastX);
int dy = (int) (event.getRawY() - mLastY);
// 更新悬浮球位置
mLayoutParams.x = mStartX + dx;
mLayoutParams.y = mStartY + dy;
mWindowManager.updateViewLayout(mFloatingView, mLayoutParams);
break;
case MotionEvent.ACTION_UP:
// 处理悬浮球点击事件
if (Math.abs(event.getRawX() - mLastX) < 10 && Math.abs(event.getRawY() - mLastY) < 10) {
Intent intent = new Intent(this, FloatingBallClickActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(intent);
// 关闭悬浮球窗口
mWindowManager.removeView(mFloatingView);
finish();
}
break;
}
return true;
}
}
```
在上面的代码中,我们创建了一个继承自 Activity 的类 FloatingActivity,作为悬浮球的容器。在 onCreate 方法中,我们设置了容器的布局、位置等属性,并添加了一个 ImageView 作为悬浮球 View。在 onTouch 方法中,我们实现了悬浮球的拖动和点击事件,并使用 WindowManager 来更新悬浮球的位置。在悬浮球点击事件中,我们启动了一个新的 Activity 处理点击事件,并关闭了悬浮球窗口。
阅读全文