Androidジェスチャー方向の判断ツール類、超簡単


目的:down時にdownXとdownYを記録し、move時に移動の方向を判断する(このクラスは上下左右4方向しか実現していない)
ブロガーはくどくど言うのが好きではなく,一言が合わないとソースを貼る.
下にソースを貼ります
public class TouchUtils {

    public static final int UP = 1;
    public static final int DOWN = 2;
    public static final int LEFT = 3;
    public static final int RIGHT = 4;

    private int downX = 0;
    private int downY = 0;

    private boolean isTouch = true;

    public TouchUtils(){}

    public TouchUtils setDownXY(int x , int y){
        this.downX = x;
        this.downY = y;
        return this;
    }

    /**  *       ,         *         actionUp()           *  * @param moveX  * @param moveY  * @return state  */  public int getDirection(int moveX,int moveY){
        if(isTouch){
            if((downY - moveY ) > Math.abs(downX - moveX)){
                return UP;
            }
            if((moveY - downY) > Math.abs(downX - moveX)){
                return DOWN;
            }
            if((downX - moveX) > Math.abs(downY - moveY)){
                return LEFT;
            }
            if((moveX - downX) > Math.abs(downY - moveY)){
                return RIGHT;
            }
            isTouch = false;
        }
        return 0;
    }

    /**  *          */  public void actionUp(){
        isTouch = true;
    }

}

Activityでの使用コール:
public class TextTouchActivity extends Activity{

    private TextView textView;
    private TouchUtils touchUtils;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = (TextView) findViewById(R.id.main_tv);
        touchUtils = new TouchUtils();
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent ev) {
        switch (ev.getAction()){
            case MotionEvent.ACTION_DOWN:
                touchUtils.setDownXY((int)ev.getX(),(int)ev.getY());
                break;
            case MotionEvent.ACTION_MOVE:
                switch (touchUtils.getDirection((int)ev.getX(),(int)ev.getY())){
                    case TouchUtils.RIGHT:
                        textView.setText(" ");
                        break;
                    case TouchUtils.LEFT:
                        textView.setText(" ");
                        break;
                    case TouchUtils.UP:
                        textView.setText(" ");
                        break;
                    case TouchUtils.DOWN:
                        textView.setText(" ");
                        break;
                }
                break;

            case MotionEvent.ACTION_UP:
                touchUtils.actionUp();
                break;
        }
        return super.dispatchTouchEvent(ev);
    }
}