确定Fling方向

时间:2013-08-05 20:41:30

标签: android android-gesture

我正在使用GestureDetector来调用onFling()。它似乎正确地检测到我的flings,因为它触发了我创建的Log消息。我正试图确定投掷的方向,但遇到了问题。传递到MotionEvent方法的onFling()个对象的x值相同,因此我无法确定方向。例如,我得到:

08-05 16:36:08.679: DEBUG/mView(14616): fling2: 131.0 131.0

当我这样做时:

Log.d("mView", "fling2: " + e1.getX() + " " + e2.getX());

在进行投掷时,我只是将手指水平移动,所以这对我没有意义。这里可能出现什么问题?

1 个答案:

答案 0 :(得分:2)

您可以使用droidQuery:https://github.com/phil-brown/droidQuery。它将真正简化您的代码并使其易于使用。以下是您在活动onCreate()中所需要的全部内容:

//global variables
private boolean isSwiping = false;
private SwipeDetector.Direction swipeDirection = null;
private View v;//set to the parent layout of the fragments.

//swipe-handling code
$.with(v).swipe(new Function() {
    @Override
    public void invoke($ droidQuery, Object... params) {
        if (params[0] == SwipeDetector.Direction.START)
            isSwiping = true;
        else if (params[0] == SwipeDetector.Direction.STOP) {
            if (isSwiping) {
                isSwiping = false;
                if (swipeDirection != null) {
                    switch(swipeDirection) {
                        case DOWN :
                            //TODO: Down swipe complete, so do something
                            break; 
                        case UP :
                            //TODO: Up swipe complete, so do something
                            break; 
                        case LEFT :
                            //TODO: Left swipe complete, so do something
                            break; 
                        case RIGHT :
                            //TODO: Right swipe complete, so do something (such as):
                            day++;
                            Fragment1 rightFragment = new Fragment1();
                            Bundle args = new Bundle();
                            args.putInt("day", day);
                            rightFragment.setArguments(args);

                            android.support.v4.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
                            transaction.replace(R.id.fragment_container, rightFragment);
                            transaction.addToBackStack(null);
                            transaction.commit();
                            break; 
                        default :
                            break; 
                    }
                }
            }
        }
        else {
            swipeDirection = (SwipeDetector.Direction) params[0];
        }
    }
});