我想触摸拖动屏幕周围的视图,触摸释放时我想将视图恢复到原点位置。
这是我的代码:
private float xCoOrdinate, yCoOrdinate;
private float top2AxOriginXCoordinate, top2AxOriginYCoordinate;
private void initControls(View view) {
top2AX = view.findViewById(R.id.top2AX);
top2AxOriginXCoordinate = top2AX.getX();
top2AxOriginYCoordinate = top2AX.getY();
addDragListener();
}
private void addDragListener() {
myView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View view, MotionEvent event) {
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
xCoOrdinate = view.getX() - event.getRawX();
yCoOrdinate = view.getY() - event.getRawY();
break;
case MotionEvent.ACTION_MOVE:
view.animate().x(event.getRawX() + xCoOrdinate).y(event.getRawY() + yCoOrdinate).setDuration(0).start();
break;
case MotionEvent.ACTION_UP:
view.animate().x(top2AxOriginXCoordinate).y(top2AxOriginYCoordinate).setDuration(500).start();
break;
default:
return false;
}
return true;
}
});
}
触摸和拖动工作完美,但当我释放触摸时它不会回到原点位置。它位于屏幕的左上角,略有左边距。我在这做错了什么?感谢任何帮助
答案 0 :(得分:1)
top2AxOriginXCoordinate = top2AX.getX();
top2AxOriginYCoordinate = top2AX.getY();
这两个变量可能是0.0,如果是,那么告诉我我会帮你