Android gesture operation example of and and left and right judgment
- 2021-07-26 08:51:15
- OfStack
This paper describes the Android gesture operation method with examples. Share it for your reference, as follows:
Android provides an interface for judging gestures, so we can realize various gesture functions according to the provided API to improve the user experience of mobile phone applications.
The following is a small Demo I wrote:
GestureActivity.Java
public class GestureActivity extends Activity {
private GestureDetector gestureDetector;
private Screen screen;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
gestureDetector = new GestureDetector(this,onGestureListener);
// Get the size of the screen
screen = GestureUtils.getScreenPix(this);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
return gestureDetector.onTouchEvent(event);
}
GestureDetector.OnGestureListener onGestureListener = new GestureDetector.SimpleOnGestureListener(){
@Override
public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
float velocityY) {
float x = e2.getX() - e1.getX();
float y = e2.getY() - e1.getY();
// Limit the number that must be crossed the screen 1/3 To be counted as crossing
float x_limit = screen.widthPixels / 3;
float y_limit = screen.heightPixels / 3;
float x_abs = Math.abs(x);
float y_abs = Math.abs(y);
if(x_abs >= y_abs){
//gesture left or right
if(x > x_limit || x < -x_limit){
if(x>0){
//right
show("right");
}else if(x
//left
show("left");
}
}
}else{
//gesture down or up
if(y > y_limit || y < -y_limit){
if(y>0){
//down
show("down");
}else if(y
//up
show("up");
}
}
}
return true;
}
};
private void show(String value){
Toast.makeText(this, value, Toast.LENGTH_SHORT).show();
}
}
GestureUtils.java
public class GestureUtils {
// Gets the size of the screen
public static Screen getScreenPix(Context context) {
DisplayMetrics dm = new DisplayMetrics();
WindowManager windowManager = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
windowManager.getDefaultDisplay().getMetrics(dm);
return new Screen(dm.widthPixels,dm.heightPixels);
}
public static class Screen{
public int widthPixels;
public int heightPixels;
public Screen(){
}
public Screen(int widthPixels,int heightPixels){
this.widthPixels=widthPixels;
this.heightPixels=heightPixels;
}
@Override
public String toString() {
return "("+widthPixels+","+heightPixels+")";
}
}
}
For more readers interested in Android related contents, please check the topics on this site: "Summary of Android File Operation Skills", "Summary of SD Card Operation Methods for Android Programming Development", "Introduction and Advanced Tutorial for Android Development", "Summary of Android Resource Operation Skills", "Summary of Android View View Skills" and "Summary of Android Control Usage"
I hope this article is helpful to everyone's Android programming.