android - 使用scrollview检测片段中的滑动手势

时间:2016-02-26 18:07:16

标签: android android-fragments fragment scrollview swipe

我实现了一个带有scrollview的片段,我想在这个片段中检测从左到右的滑动。我使用以下代码检测滑动事件:

public View onCreateView(LayoutInflater inflater, ViewGroup container,
                         Bundle savedInstanceState) {

    final GestureDetector gesture = new GestureDetector(getActivity(),
            new GestureDetector.SimpleOnGestureListener() {

                @Override
                public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
                                       float velocityY) {
                    Log.i("SWIPE", "onFling has been called!");
                    final int SWIPE_MIN_DISTANCE = 120;
                    final int SWIPE_MAX_OFF_PATH = 250;
                    final int SWIPE_THRESHOLD_VELOCITY = 200;
                    try {
                        if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH) {
                            return false;
                        }

                        if (e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                            Log.i("SWIPE", "Right to Left");
                        }

                        else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                            Log.i("SWIPE", "Left to Right");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                    return super.onFling(e1, e2, velocityX, velocityY);
                }
            });

    container.setOnTouchListener(new View.OnTouchListener()

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


    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_blank, container, false);
}

我在布局中没有滚动视图测试了这段代码,它工作正常。一旦我在布局中插入滚动视图,就会检测到滑动事件停止。

<ScrollView xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="com.doutvisions.teste.BlankFragment"
android:id="@+id/scrollView1">


<TextView
    android:gravity="center"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:text="@string/hello_blank_fragment" />

</ScrollView>

有人可以帮忙吗?我很感激。

0 个答案:

没有答案