场景描述:
界面上有一个浮动按钮,可以用手指拖动,点击该按钮触发事件,我这里是启动扫描,留了一个空实现。
class="java" name="code">
private WindowManager wm;
private View view;//浮动按钮
/**
* 添加悬浮View
*/
protected void createFloatView() {
int w=200;//大小
wm = (WindowManager) getSystemService(Context.WINDOW_SERVICE);
view = getLayoutInflater().inflate(R.layout.scanball, null);
final WindowManager.LayoutParams params = new WindowManager.LayoutParams();
params.type=LayoutParams.TYPE_BASE_APPLICATION;//所有程序窗口的“基地”窗口,其他应用程序窗口都显示在它上面。
params.flags = LayoutParams.FLAG_NOT_TOUCH_MODAL|LayoutParams.FLAG_NOT_FOCUSABLE;
params.format = PixelFormat.TRANSLUCENT;// 不设置这个弹出框的透明遮罩显示为黑色
params.width = w;
params.height = w;
params.gravity = Gravity.TOP|Gravity.LEFT;
int screenWidth = getResources().getDisplayMetrics().widthPixels;
int screenHeight = getResources().getDisplayMetrics().heightPixels;
params.x = screenWidth-w;
params.y = screenHeight-w-160;
view.setBackgroundColor(Color.TRANSPARENT);
view.setVisibility(View.VISIBLE);
view.setOnTouchListener(new OnTouchListener() {
// 触屏监听
float lastX, lastY;
int oldOffsetX,oldOffsetY;
int tag = 0;//悬浮球 所需成员变量
@Override
public boolean onTouch(View v, MotionEvent event) {
final int action = event.getAction();
float x = event.getX();
float y = event.getY();
if(tag == 0){
oldOffsetX= params.x; // 偏移量
oldOffsetY = params.y; // 偏移量
}
if (action == MotionEvent.ACTION_DOWN) {
lastX = x;
lastY = y;
}
else if (action == MotionEvent.ACTION_MOVE) {
params.x += (int) (x - lastX)/3; //减小偏移量,防止过度抖动
params.y += (int) (y - lastY)/3; //减小偏移量,防止过度抖动
tag = 1;
wm.updateViewLayout(view, params);
}
else if (action == MotionEvent.ACTION_UP){
int newOffsetX = params.x;
int newOffsetY = params.y;
//只要按钮一动位置不是很大,就认为是点击事件
if(Math.abs(oldOffsetX-newOffsetX)<=20&&Math.abs(oldOffsetY-newOffsetY)<=20){
//dosomething
scan();
}else{
tag = 0;
}
}
return true;
}
});
wm.addView(view, params);
}
/**
* 点击浮动按钮触发事件,需要override该方法
*/
protected void scan(){
}
/**
* 将悬浮View从WindowManager中移除
*/
protected void removeFloatView() {
if (wm != null&&view!=null) {
wm.removeView(view);
view = null;
wm = null;
}
}