如何在片段中使用setOnTouchListener?

时间:2017-10-21 07:42:48

标签: java android fragment

我有一个名为ProfileFragment.java的片段,我想通过调用类OnSwipeTouchListener来监听触摸手势。

以下是来自ProfileFragment.java的代码片段:

rootLayout.setOnTouchListener(new OnSwipeTouchListener(ProfileFragment.this) {

            @Override
            public void onSwipeTop() {
                super.onSwipeTop();
                //folder_gridview.setVisibility(View.INVISIBLE);

                // do something
            }
});

从上面的代码中我得到了这个错误:

  

OnSwipeTouchListener中的OnSwipeTouchListener(android.content.Context)无法应用于(com.mydomain.sample.ProfileFragment)

以下是OnSwipeTouchListener.java类的代码:

public class OnSwipeTouchListener implements OnTouchListener {

    private final GestureDetector gestureDetector;

    public OnSwipeTouchListener(Context ctx) {
        gestureDetector = new GestureDetector(ctx, new GestureListener());
    }

    @Override
    public boolean onTouch(View v, MotionEvent event) {
        return gestureDetector.onTouchEvent(event);
    }

    private final class GestureListener extends SimpleOnGestureListener {

        private static final int SWIPE_THRESHOLD = 1;
        private static final int SWIPE_VELOCITY_THRESHOLD = 1;

        @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }

        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            boolean result = false;
            try {
                float diffY = e2.getY() - e1.getY();
                float diffX = e2.getX() - e1.getX();
                if (Math.abs(diffX) > Math.abs(diffY)) {
                    if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                        if (diffX > 0) {
                            onSwipeRight();
                        } else {
                            onSwipeLeft();
                        }
                    }
                    result = true;
                } else if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
                    if (diffY > 0) {
                        onSwipeBottom();
                    } else {
                        onSwipeTop();
                    }
                }
                result = true;

            } catch (Exception exception) {
                exception.printStackTrace();
            }
            return result;
        }
    }

    public void onSwipeRight() {
    }

    public void onSwipeLeft() {
    }

    public void onSwipeTop() {
    }

    public void onSwipeBottom() {
    }
}

我能够获得上面的代码来处理一个活动,但无法让它在片段上工作。如何让它在片段上工作?

1 个答案:

答案 0 :(得分:1)

您必须在context上传递OnSwipeTouchListener个参数,而是传递不会从ProfileFragment.this继承的片段context

您应该将getActivity()作为参数传递给OnSwipeTouchListener,如下所示:

rootLayout.setOnTouchListener(new OnSwipeTouchListener(getActivity()) {
    /*rest of your code*/ 
});