有的时候的悬浮按钮并不需要一直在后台运行,而且写service的悬浮按钮的demo也很多,最近碰到一个需求,只要在一个界面出现悬浮按钮,本着代码越少越好的原则,摸索了好几个方法来写这样需求,最后将最简单的和大家分享出来,代码量不多,主要就是重写view的setOnTouchListener,先看效果:
代码比较简单,其实就是一个button,下面上代码:
DisplayMetrics dm = getResources().getDisplayMetrics();
final Button btn = (Button) findViewById(R.id.btn);
final int screenWidth = dm.widthPixels;
final int screenHeight = dm.heightPixels-dip2px(this,60);
btn.setOnTouchListener(new View.OnTouchListener() {
int lastX, lastY;
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
lastX = (int) event.getRawX();// 获取触摸事件触摸位置的原始X坐标
lastY = (int) event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
int dx = (int) event.getRawX() - lastX;
int dy = (int) event.getRawY() - lastY;
int l = v.getLeft() + dx;
int b = v.getBottom() + dy;
int r = v.getRight() + dx;
int t = v.getTop() + dy;
// 下面判断移动是否超出屏幕
if (l < 0) {
l = 0;
r = l + v.getWidth();
}
if (t < 0) {
t = 0;
b = t + v.getHeight();
}
if (r > screenWidth) {
r = screenWidth;
l = r - v.getWidth();
}
if (b > screenHeight) {
b = screenHeight;
t = b - v.getHeight();
}
v.layout(l, t, r, b);
lastX = (int) event.getRawX();
lastY = (int) event.getRawY();
v.postInvalidate();
break;
case MotionEvent.ACTION_UP:
break;
}
return false;
}
});
这个就不解释了吧
public static int dip2px(Context context, float dpValue) {
final float scale = context.getResources().getDisplayMetrics().density;
return (int) (dpValue * scale + 0.5f);
}
写的不好多有指教,邮箱jttangjiajun@163.com