Last active
February 14, 2023 12:36
-
-
Save perry14/0770ec815774cee688921a0075f9290b to your computer and use it in GitHub Desktop.
android: move a view on touch move
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
View.OnTouchListener touchListener = new View.OnTouchListener() { | |
private int lastX = 0; | |
private int lastY = 0; | |
@Override | |
public boolean onTouch(View v, MotionEvent event) { | |
switch (event.getAction()) { | |
case MotionEvent.ACTION_DOWN: { | |
lastX = (int) event.getRawX(); | |
lastY = (int) event.getRawY(); | |
break; | |
} | |
case MotionEvent.ACTION_MOVE: { | |
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: { | |
break; | |
} | |
} | |
return true; | |
} | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment