简体   繁体   中英

How to detect movement to the left, right, up and down

I wonder if it's possible to use the onTouch method below to detect if the user is moving the finger to the left, right, up och down on the screen. I have a grid with objects and I just want the user to be able to move one of this object in four directions.

My idea was to use the Action_Down event to get the X and Y position and then check all objects in a list to see which object that is whitin the X and Y value. Then by using the Action_Move start moving it in one of the directions.

    @Override
public boolean onTouch(View v, MotionEvent event) {

    switch (event.getAction()) {

    case MotionEvent.ACTION_DOWN:
        Log.i("test","Down");
        break;

    case MotionEvent.ACTION_POINTER_UP:

        break;

    case MotionEvent.ACTION_MOVE:
        Log.i("test","Move");
        break;
    }
public class MainActivity extends Activity {
...
// This example shows an Activity, but you would use the same approach if
// you were subclassing a View.
@Override
public boolean onTouchEvent(MotionEvent event){ 

    int action = MotionEventCompat.getActionMasked(event);

    switch(action) {
        case (MotionEvent.ACTION_DOWN) :
            Log.d(DEBUG_TAG,"Action was DOWN");
            return true;
        case (MotionEvent.ACTION_MOVE) :
            Log.d(DEBUG_TAG,"Action was MOVE");
            return true;
        case (MotionEvent.ACTION_UP) :
            Log.d(DEBUG_TAG,"Action was UP");
            return true;
        case (MotionEvent.ACTION_CANCEL) :
            Log.d(DEBUG_TAG,"Action was CANCEL");
            return true;
        case (MotionEvent.ACTION_OUTSIDE) :
            Log.d(DEBUG_TAG,"Movement occurred outside bounds " +
                    "of current screen element");
            return true;      
        default : 
            return super.onTouchEvent(event);
    }      
}

For more details see this link , You can also use (and I will recommend that) OnFling() of GestureDetector for an example of that visit this link ...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM