最近在项目中用到了可拖动悬浮组件,在网上搜了下,大概实现思路是获得全局的上下文对象来获取WindowManage,让wm挂载一个layout,实现layout root节点的单击,双击及滑动事件,不多说,上源码。
public class FloatView{
static FloateView instance = new FloatView();
static float EVENT_NULL = -1;
public static FloatView getInstance(){
return instance;
}
View view;
ImageView ivIcon;
Context context;
WindowManager wm;
float currentX = EVENT_NULL,currentY = EVENT_NU:
float startX = startY = EVENT_NULL:
int width, height;
boolean isShow = false;
private FloatView(){
//获得全局Context
context = getApplicationContext();
wm = (WindowManager)context.getSystemService(Context.WINDOW_SERVICE);
}
public void showIcon(){
createIcon();
show();
}
void show(){
WindowManager.LayoutParams lp = new WindowManager.LayoutParams();
lp.flags |= WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL;
lp.flags |= WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE;
lp.flags |= WindowManager.LayoutParams.FLAG_WATCH_OUTSIDE_TOUCH;
lp.format = PxielFormat.RGBA_8888;
lp.type = WindowManager.LayoutParams.TYPE_SYSYTEM_ALERT;
lp.width = ViewGroup.LayoutParams.WRAP_CONTENT;
lp.height = ViewGroup.LayoutParams.WRAP_CONTENT;
lp.gravity = Gravity.CENTER_VERTICAL | Gravity.LEFT;
wm.addView(view, lp);
isShow = true;
}
void createIcon(){
//加载布局
view = View.inflate(context,…);
ivIcon = view.findViewById();
final GestureDetector gd = new GestureDetector(context,
new SimpleOnGestureDetector(){
public boolean onDoubleTap(MotionEvent e){
}
public boolean onSingleTapConfirmed(MotionEvent e){}
public boolean onScroll(MotionEvent e1, MotionEvent e2, float x, float y){
update(currentX - startX, currentY - startY);
startX = currentX;
startY = currentY;
}
});
view.setOnTouchListener(new View.OnTouchListener(){
public boolean onTouch(View v, MotionEvent event){
currentX = event.getRawX();
currentY = event.getRawY();
if(event.getAction == MotionEvent.ACTION_DOWN) {
startX = currentX;
startY = currentY;
}
return gd.onTouchEvent(event);
}
});
width = 50;
height = 50;
}
}
void update(float x, float y){
if(isShow){
WindowManger.LayoutParams lp = view.getLayoutParams();
lp.x = (int)lp.x + x;
lp.y = (int)lp.y + y;
wm.updateViewlayout(view, lp);
}
}
void dismiss(){
if(isShow){
wm.remove(view);
view = null;
}
isShow = false;
}
}