onFling事件未被触发

时间:2017-04-26 01:09:09

标签: android

我正在测试我的活动的左右滑动。我有以下代码:

public class MainActivity extends AppCompatActivity implements LocationListener, GestureDetector.OnGestureListener {
   ...
   private GestureDetectorCompat gestureDetector;
   ...
   protected void onCreate(Bundle savedInstanceState) {
     ...
     gestureDetector = new GestureDetectorCompat(this, this);
     ...
   }

   public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {

        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) {
            // right to left swipe
            Toast.makeText(getApplicationContext(), "right to left swipe", Toast.LENGTH_LONG);

        } else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE
                && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
            Toast.makeText(getApplicationContext(), "left to right swipe", Toast.LENGTH_LONG);
        }

    Log.i("EVENT:", "Event triggered");
    return true;
  }


  public boolean onTouchEvent(MotionEvent event) {
    gestureDetector.onTouchEvent(event);

    return super.onTouchEvent(event);
  }

我希望在向左和向右滑动时调用onFling方法。但是我在onFling中的所有消息都没有被调用。当我看到控制台时,我只看到了这一点:

I/ViewRootImpl: ViewRoot's Touch Event : ACTION_DOWN
I/ViewRootImpl: ViewRoot's Touch Event : ACTION_UP
I/ViewRootImpl: ViewRoot's Touch Event : ACTION_DOWN
I/ViewRootImpl: ViewRoot's Touch Event : ACTION_UP

我可能做错了什么?

1 个答案:

答案 0 :(得分:0)

当您遇到此问题时,很可能是由于您的布局中存在元素。我有一个RelativeLayout的子元素,与父母的身高和宽度相匹配:

<ListView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerHorizontal="true" android:id="@+id/listView" android:layout_alignParentTop="true"/>

当我删除它时,调用了onFling事件。

相关问题