如何检测向左,向右,向上和向下的运动

时间:2013-05-21 05:27:15

标签: android

我想知道是否可以使用下面的onTouch方法检测用户是否正在将手指向左,向右,向上移动到屏幕上。我有一个带有对象的网格,我只希望用户能够在四个方向上移动该对象中的一个。

我的想法是使用Action_Down事件获取X和Y位置,然后检查列表中的所有对象,以查看哪个对象在X和Y值中。然后使用Action_Move开始在其中一个方向上移动它。

    @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;
    }

1 个答案:

答案 0 :(得分:0)

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);
    }      
}

有关详细信息,请参阅this link,您还可以使用(我将建议) GestureDetector OnFling()作为该访问的示例{ {3}} ...