Android 悬浮组件

最近在项目中用到了可拖动悬浮组件,在网上搜了下,大概实现思路是获得全局的上下文对象来获取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;
}
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值