1.在onCreate里写
DisplayMetrics dm = getResources().getDisplayMetrics();
screenWidth = dm.widthPixels;
screenHeight = dm.heightPixels - 50;
btn_toPC.setOnTouchListener(this); //btn_toPC为要拖动的按钮
2.覆写onTouch方法
//touch to drag
@Override
public boolean onTouch(View v, MotionEvent event) {
int action=event.getAction();
Log.i("touch", "Touch:" + action);
switch(action) {
case MotionEvent.ACTION_DOWN:
lastX = (int)event.getRawX();
lastY = (int)event.getRawY();
isclick = false;//当按下的时候设置isclick为false
startTime = System.currentTimeMillis();
break;
case MotionEvent.ACTION_MOVE:
isclick = true;//当按钮被移动的时候设置isclick为true
int dx = (int)event.getRawX() - lastX;
int dy = (int)event.getRawY() - lastY;
int left = v.getLeft() + dx;
int top = v.getTop() + dy;
int right = v.getRight() + dx;
int bottom = v.getBottom() + dy;
if(left < 0) {
left = 0;
right = left + v.getWidth();
}
if(right > screenWidth) {
right = screenWidth;
left = right - v.getWidth();
}
if(top < 0) {
top = 0;
bottom = top + v.getHeight();
}
if(bottom > screenHeight) {
bottom = screenHeight;
top = bottom - v.getHeight();
}
v.layout(left, top, right, bottom);
lastX = (int) event.getRawX();
lastY = (int) event.getRawY();
break;
case MotionEvent.ACTION_UP:
endTime = System.currentTimeMillis();
//当从点击到弹起小于半秒的时候,则判断为点击,如果超过则不响应点击事件
if ((endTime - startTime) > 0.1 * 1000L) {
isclick = true;
} else {
isclick = false;
}
System.out.println("执行顺序up");
break;
}
return isclick;
}
//—————— end ——————
android 按钮拖动并点击判断
最新推荐文章于 2021-05-26 09:07:46 发布