1
I found this method on the internet to detect movement, but I would like when it moves right it executes a command (example changes button color), but I’m having trouble implementing this code if anyone knows to give me a strength, I thank you from now on.
private String TAG = GestureActivity.class.getSimpleName();
float initialX, initialY;
@Override
public boolean onTouchEvent(MotionEvent event) {
//mGestureDetector.onTouchEvent(event);
int action = event.getActionMasked();
switch (action) {
case MotionEvent.ACTION_DOWN:
initialX = event.getX();
initialY = event.getY();
Log.d(TAG, "Action was DOWN");
break;
case MotionEvent.ACTION_MOVE:
Log.d(TAG, "Action was MOVE");
break;
case MotionEvent.ACTION_UP:
float finalX = event.getX();
float finalY = event.getY();
Log.d(TAG, "Action was UP");
if (initialX < finalX) {
Log.d(TAG, "Left to Right swipe performed");
}
if (initialX > finalX) {
Log.d(TAG, "Right to Left swipe performed");
}
if (initialY < finalY) {
Log.d(TAG, "Up to Down swipe performed");
}
if (initialY > finalY) {
Log.d(TAG, "Down to Up swipe performed");
}
break;
case MotionEvent.ACTION_CANCEL:
Log.d(TAG,"Action was CANCEL");
break;
case MotionEvent.ACTION_OUTSIDE:
Log.d(TAG, "Movement occurred outside bounds of current screen element");
break;
}
return super.onTouchEvent(event);
}
Rodolfo, could you describe your difficulty? In your code, "move to the right" is the first
if
(you can replaceLog.d(TAG, "Left to Right swipe performed");
by the code to change the button color or whatever you want.– Anthony Accioly
I don’t quite understand your question. As I understand it, I think this link will answer your questions: http://stackoverflow.com/questions/6645537/how-to-detect-the-swipe-left-right-in-android Good luck!
– Gustavo Bitencourt
The first line uses reflection to catch the class name
GestureActivity
. The parameter Motionevent is an event containing the current position and historical data of the movement. You must override this methodonTouchEvent
in aActivity
or create and link aOnTouchListener
to your view. It in turn will create the event and shoot to yourlistener
.– Anthony Accioly
For more concrete help (to put your code to work), I suggest you create a mvce pointing exactly where your doubts lie.
– Anthony Accioly
@Anthonyaccioly worked code, but it does not work at first and need to make several attempts.
– Vale
if you know another method for this purpose, and can help me
– Vale
Rodolfo, my suggestion is to use the
GestureDetector
along with theGestureDetector.OnGestureListener
, can detect the gesture byonFling
and/or theonScroll
, verifying the displacement at coordinate y.– Wakim