手势操作开发

1.手势开发中,OnGestureListener,但需要重写其中的全部方法。为了方便,google工程师,开发了另一个类GestureDetector.SimpleOnGestureListener

通过该类,可以实现自己需要的方法


2.在activity中使用,先实例化手势实现类,然后通过在Ontouchevent中调用


import android.content.Context;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.widget.Toast;


public class MyGestureListener extends GestureDetector.SimpleOnGestureListener{


Context context ;
MyGestureListener(Context context){
this.context = context;
}
@Override
public void onLongPress(MotionEvent e) {
Toast.makeText(context, "longpress", 1).show();
super.onLongPress(e);
}

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

if(e1.getX()-e2.getX() > 12 && Math.abs(velocityX) > 10){
      Toast.makeText(context, "turn left", Toast.LENGTH_SHORT).show();
       
        }else if(e2.getX() - e1.getX() > 12 && Math.abs(velocityX) > 10){
      Toast.makeText(context, "turn right", Toast.LENGTH_SHORT).show();
     
        }else if(e1.getY()-e2.getY() > 20 && Math.abs(velocityY) > 10){
        Toast.makeText(context, "turn up", Toast.LENGTH_SHORT).show();
       
        }else if(e2.getY()-e1.getY() > 20 && Math.abs(velocityY) > 10){
        Toast.makeText(context, "turn down", Toast.LENGTH_SHORT).show();
        }
     
      return false;

}

@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
float distanceY) {

return super.onScroll(e1, e2, distanceX, distanceY);
}
}




Activity类

import android.app.Activity;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MotionEvent;


public class MainActivity extends Activity {
private GestureDetector mGestureDetector;


@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mGestureDetector = new GestureDetector(this, new MyGestureListener(this));
}


@Override
public boolean onTouchEvent(MotionEvent event) {


if (mGestureDetector.onTouchEvent(event))
return true;
else
return false;
}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}


}

你可能感兴趣的:(手势操作开发)