不多说直接代码,看注释就成。
FloatView:
public class FloatView extends View {
private String TAG = getClass().getName();
private float mTouchStartX;
private float mTouchStartY;
private float x;
private float y;
private WindowManager manager;
private WindowManager.LayoutParams params;
public FloatView(Context context) {
super(context);
// 获取WindowManager
manager = (WindowManager) context
.getSystemService(Context.WINDOW_SERVICE);
// 设置LayoutParams(全局变量)相关参数
params = new WindowManager.LayoutParams();
params.type = WindowManager.LayoutParams.TYPE_SYSTEM_ALERT; // 系统提示类型,重要
params.format = 1;
params.flags = WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE; // 不能抢占聚焦点
params.flags = params.flags
| WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH;
params.flags = params.flags
| WindowManager.LayoutParams.FLAG_LAYOUT_NO_LIMITS; // 排版不受限制
params.alpha = 1.0f;
params.gravity = Gravity.LEFT | Gravity.TOP; // 调整悬浮窗口至左上角
// 以屏幕左上角为原点,设置x、y初始值
params.x = 0;
params.y = 0;
// 设置悬浮窗口长宽数据
params.width = 140;
params.height = 140;
// 显示myFloatView图像
manager.addView(this, params);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
// 获取相对屏幕的坐标,即以屏幕左上角为原点
x = event.getRawX();
y = event.getRawY() - 25; // 25是系统状态栏的高度
Log.i("currP", "currX" + x + "====currY" + y);
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
// 获取相对View的坐标,即以此View左上角为原点
mTouchStartX = event.getX();
mTouchStartY = event.getY();
break;
case MotionEvent.ACTION_MOVE:
updateViewPosition();
break;
case MotionEvent.ACTION_UP:
updateViewPosition();
mTouchStartX = mTouchStartY = 0;
break;
}
return true;
}
private void updateViewPosition() {
// 更新浮动窗口位置参数
params.x = (int) (x - mTouchStartX);
params.y = (int) (y - mTouchStartY);
manager.updateViewLayout(this, params);
}
public void clear() {
manager.removeView(this);
}
}
使用方式MainActivity:
public class MainActivity extends Activity {
private FloatView mLayout;
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
showView();
}
private void showView() {
mLayout = new FloatView(this);
mLayout.setBackgroundResource(R.drawable.ic_launcher);
}
@Override
public void onDestroy() {
super.onDestroy();
// 在程序退出(Activity销毁)时销毁悬浮窗口
mLayout.clear();
}
}