试图让OnFling工作

时间:2013-01-06 08:34:10

标签: android swipe ontouchevent uiswipegesturerecognizer swipe-gesture

我知道有很多关于这个话题的问题。我已经看了他们中的大多数,但我仍然无法调试我的代码。它不会检测滑动。我是Android编程和Java的初学者,所以请不要过于挑剔。

  • 我有一个简单的线性布局,有一个填充整个布局的按钮。每次单击该按钮时,它的值都会增加1。
  • 我正在尝试左右滑动。我的基本疑问是我应该使用Button或Linear Layout实现setOnTouchListener吗?
  • 我见过人们使用OnGestureListener和OnTouchListener。哪个更好?

    public class MainActivity extends Activity implements OnClickListener{
    
    public Button increment;
    public int cnt= 0;
    private static final int SWIPE_MIN_DISTANCE = 80;
    private static final int SWIPE_THRESHOLD_VELOCITY = 40;
    GestureDetector gestureDetector;
    LinearLayout swipe_layout= (LinearLayout)findViewById(R.id.linear);
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        increment= (Button)findViewById(R.id.numberkey);
        increment.setOnClickListener(this);
        setDisplay(0);
        gestureDetector= new GestureDetector(this, new Detector());
        increment.setOnTouchListener(new OnTouchListener() {
    
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                gestureDetector.onTouchEvent(event);
                return true;
            }
        });
    
    }
    
    @Override
    public void onClick(View v) 
    {
        setDisplay(cnt++);
    }
    
    private void setDisplay(int i) 
    {   increment.setText(String.valueOf(i));
    }
    
    class Detector extends SimpleOnGestureListener {
    
    @Override
        public boolean onDown(MotionEvent e) {
            return true;
        }
    
    
        @Override
        public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float            velocityY) {
                // right to left swipe
                if(e1.getX() - e2.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY)
                   Toast.makeText(MainActivity.this, "Left Swipe", Toast.LENGTH_SHORT).show();
    
                else if (e2.getX() - e1.getX() > SWIPE_MIN_DISTANCE && Math.abs(velocityX) > SWIPE_THRESHOLD_VELOCITY) {
                    Toast.makeText(MainActivity.this, "Right Swipe", Toast.LENGTH_SHORT).show();
                }
            return false;
        }
    
    }
    

    }

提前致谢。

1 个答案:

答案 0 :(得分:0)

移动

LinearLayout swipe_layout= (LinearLayout)findViewById(R.id.linear); 

在活动setContentView(R.layout.activity_main);之后,因为您在设置当前活动的布局

之前尝试查找视图

并将布局设置为onTouchListener

LinearLayout swipe_layout;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    swipe_layout= (LinearLayout)findViewById(R.id.linear);

    swipe_layout.setOnTouchListener(new OnTouchListener() {

     @Override
       public boolean onTouch(View v, MotionEvent event) {

         return true;
    }
  });