andoird -> Use Activity's onTouchEvent method to monitor finger sliding up, down, left and right

 

 

Reprinted from:  http://blog.csdn.net/qiantujava/article/details/9903891

 

Use Activity's onTouchEvent method to monitor finger sliding up, down, left and right

The ontouchEvent method of Activity is applied to monitor the finger click event. When the finger slides, it will be pressed first, slipped to another place and then lifted. We can calculate which direction the user is sliding according to the coordinates of the pressed and lifted coordinates. .

 

[java]  view plain copy  
 
  1. package com.example.testtt;  
  2.   
  3. import android.app.Activity;  
  4. import android.os.Bundle;  
  5. import android.view.MotionEvent;  
  6. import android.widget.Toast;  
  7.   
  8. publicclass MainActivity extends Activity {   
  9.     //The point where the finger is pressed is (x1, y1) The point where the finger leaves the screen is (x2, y2)  
  10.     float x1 = 0;  
  11.     float x2 = 0;  
  12.     float y1 = 0;  
  13.     float y2 = 0;  
  14.       
  15.     @Override  
  16.     protectedvoid onCreate(Bundle savedInstanceState) {   
  17.         super .onCreate (savedInstanceState);  
  18.         setContentView(R.layout.activity_main);  
  19.     }  
  20.       
  21.     @Override  
  22.     publicboolean onTouchEvent(MotionEvent event) {   
  23.         //Inherited Activity's onTouchEvent method, directly listening for click events  
  24.         if(event.getAction() == MotionEvent.ACTION_DOWN) {  
  25.             // when the finger is pressed  
  26.             x1 = event.getX();  
  27.             y1 = event.getY();  
  28.         }  
  29.         if(event.getAction() == MotionEvent.ACTION_UP) {  
  30.             // when the finger leaves  
  31.             x2 = event.getX();  
  32.             y2 = event.getY();  
  33.             if(y1 - y2 > 50) {  
  34.                 Toast.makeText(MainActivity.this"向上滑", Toast.LENGTH_SHORT).show();  
  35.             } else if(y2 - y1 > 50) {  
  36.                 Toast.makeText(MainActivity.this"向下滑", Toast.LENGTH_SHORT).show();  
  37.             } else if(x1 - x2 > 50) {  
  38.                 Toast.makeText(MainActivity.this"向左滑", Toast.LENGTH_SHORT).show();  
  39.             } else if(x2 - x1 > 50) {  
  40.                 Toast.makeText(MainActivity.this"向右滑", Toast.LENGTH_SHORT).show();  
  41.             }  
  42.         }  
  43.         returnsuper.onTouchEvent(event);   
  44.     }  
  45.       
  46.       
  47. }  

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326359574&siteId=291194637
Recommended