我有一个ImageView,它正在用作系统覆盖按钮,但问题出在移动按钮和单击按钮之间。我将在下面为onTouchListener发布代码,但实际上发生的是每次用户尝试单击IV时,除非他们设法达到图像的完美中心,否则ACTION_MOVE会覆盖ACTION_UP的代码。当用户只是点击按钮时,我正在尝试截屏,这就是为什么它仅触发ACTION_DOWN的原因。我尝试过的所有操作都不起作用,或者最终导致IV每次按时在屏幕上缓慢爬行。任何帮助都将不胜感激,即使它只是到另一个SO或教程的链接,因为我的整个应用程序几乎都取决于这种行为。
chatHeadImage.setOnTouchListener(new View.OnTouchListener() {
private int lastAction;
private int initialX;
private int initialY;
private float initialTouchX;
private float initialTouchY;
@Override
public boolean onTouch(View v, MotionEvent event) {
switch(event.getAction()){
case MotionEvent.ACTION_DOWN:
//remember the initial position
initialX = params.x;
initialY = params.y;
//get the touch location
initialTouchX = event.getRawX();
initialTouchY = event.getRawY();
lastAction = event.getAction();
return true;
case MotionEvent.ACTION_UP:
//As we implemented on touch listener with ACTION_MOVE,
//we have to check if the previous action was ACTION_DOWN
//to identify if the user clicked the view or not
if(lastAction == MotionEvent.ACTION_DOWN){
Toast.makeText(ChatHeadService.this,
"Overlay pressed",
Toast.LENGTH_SHORT).show();
}
lastAction = event.getAction();
return true;
case MotionEvent.ACTION_MOVE:
//Calculate the X and Y coordinates of the view
params.x = initialX + (int)(event.getRawX() - initialTouchX);
params.y = initialY + (int)(event.getRawY() - initialTouchY);
//Update the layout with new X & Y coordinate
mWindowManager.updateViewLayout(mChatHeadView, params);
lastAction = event.getAction();
return true;
}
return false;
}
});