如何检测左右上下的移动



我想知道是否有可能使用下面的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;
    }
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);
    }      
}
你也可以使用(我建议)OnFling() gestredetector 的一个例子,访问这个链接…

最新更新