在Android中向左滑动或向右滑动

时间:2014-04-25 15:53:01

标签: android swipe

我已经实现了这种编码,以便在检测到滑动时显示计数的增量。如果从左到右,它的数量会增加,否则减少。但是,每当我尝试运行它时,它会显示一些日志cat错误。请帮忙

package com.example.tc;

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.view.GestureDetectorCompat;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.TextView;
import android.widget.Toast;

public class SelectFilterActivity extends Activity implements OnClickListener{
    private static final int SWIPE_MIN_DISTANCE = 120;
    private static final int SWIPE_MAX_OFF_PATH = 250;
    private static final int SWIPE_THRESHOLD_VELOCITY = 200;
    final TextView countTextView = (TextView) findViewById(R.id.TextViewCount);
    View.OnTouchListener gestureListener;
    private int mCount = 0;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        /* ... */

        // Gesture detection
        final GestureDetectorCompat gdc = new GestureDetectorCompat(this, new MyGestureDetector());
        gestureListener = new View.OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                return gdc.onTouchEvent(event);
            }
        };

    }

    class MyGestureDetector extends SimpleOnGestureListener {
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
            try {
                if (Math.abs(e1.getY() - e2.getY()) > SWIPE_MAX_OFF_PATH)
                    return false;
                // right to left swipe
                if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                   Toast.makeText(SelectFilterActivity.this, "Left Swipe", Toast.LENGTH_SHORT).show();
                   //mCount++;
                   // countTextView.setText(""+mCount+"");
                }  else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                   Toast.makeText(SelectFilterActivity.this, "Right Swipe", Toast.LENGTH_SHORT).show();
                    //mCount--;
                   // countTextView.setText(""+mCount+"");
                }
            } catch (Exception e) {
                // nothing
            }
            return false;
        }
            @Override
        public boolean onDown(MotionEvent e) {
              return true;
        }
    }
    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub

    }
}

0 个答案:

没有答案