我有一个名为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() {
    }
}


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

最佳答案

您必须在context上传递OnSwipeTouchListener参数,但要传递不继承自ProfileFragment.this的片段context

您应该像这样在getActivity()上将OnSwipeTouchListener作为参数传递:

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

关于java - 如何在 fragment 中使用setOnTouchListener?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46861172/

10-12 04:37