Gesture trong Android



Android cung cấp nhiều kiểu sự kiện touch màn hình như những thao tác vuốt, kéo, thả, chạm, …. Chúng còn được biết với tên gọi là Gesture, và có thể nói đây là phần hay nhất của Smartphone.

Android cung cấp lớp GestureDetector để thu nhận các sự kiện di chuyển và nói cho chúng ta rằng các sự kiện này tương ứng với các Gesture hoặc không. Để sử dụng nó, bạn cần tạo một đối tượng GestureDetector và sau đó kế thừa lớp khác với GestureDetector.SimpleOnGestureListener để hoạt động như là một Listener và ghi đè một số phương thức. Cú pháp như sau: −

GestureDetector myG;
myG = new GestureDetector(this,new Gesture());
   
   class Gesture extends GestureDetector.SimpleOnGestureListener{
      public boolean onSingleTapUp(MotionEvent ev) {
   }
   
   public void onLongPress(MotionEvent ev) {
   }
   
   public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX,
   float distanceY) {
   }
   
   public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX,
   float velocityY) {
   }
}
}

Xử lý Pinch Gesture

Android cung cấp lớp ScaleGestureDetector để xử lý các Gesture như pinch, … Để sử dụng nó, bạn cần khởi tạo một đối tượng của lớp này. Cú pháp là: −

ScaleGestureDetector SGD;
SGD = new ScaleGestureDetector(this,new ScaleListener());

Tham số đầu tiên là ngữ cảnh và tham số thứ hai là Event Listener. Chúng ta phải định nghĩa Event Listener và ghi đè một hàm là. OnTouchEvent . Cú pháp như sau: −

public boolean onTouchEvent(MotionEvent ev) {
   SGD.onTouchEvent(ev);
   return true;
}private class ScaleListener extends ScaleGestureDetector.SimpleOnScaleGestureListener {
   @Override
   public boolean onScale(ScaleGestureDetector detector) {
      float scale = detector.getScaleFactor();
      return true;
   }
}

Ngoài Pinch Gesture, còn có một số phương thức khác để thông báo các sự kiện touch khác. Đó là: −

Stt Phương thức & Miêu tả
1 getEventTime()

Phương thức này lấy thời gian sự kiện của sự kiện hiện tại đang được xử lý

2 getFocusX()

Phương thức lấy tọa độ X của tiêu điểm Gesture hiện tại

3 getFocusY()

Phương thức lấy tọa độ Y của tiêu điểm Gesture hiện tại

4 getTimeDelta()

Phương thức này trả về sự khác nhau về thời gian giữa scale event trước và scale event sau

5 isInProgress()

Phương thức này trả về true nếu một scale gesture là đang tiến hành

6 onTouchEvent(MotionEvent event)

Phương thức này chấp nhận MotionEvents và gửi sự kiện khi thích hợp

Ví dụ

Ví dụ sau minh họa sự sử dụng của lớp ScaleGestureDetector. Nó tạo một ứng dụng cơ bản để bạn phóng to và thu nhỏ thông qua Pinch Gesture.

Để thử nghiệm ví dụ này, bạn cần chạy trên thiết bị thật sự hoặc trong một Emulator với sự kiện touch màn hình được kích hoạt.

Sau đây là nội dung của Main Activity file đã được sửa đổi: src/MainActivity.java.

package com.example.sairamkrishna.myapplication;import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;import android.graphics.Bitmap;
import android.graphics.Matrix;import android.os.BatteryManager;
import android.os.Bundle;import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.ScaleGestureDetector;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;import java.util.ArrayList;
import java.util.Set;public class MainActivity extends Activity {
   private ImageView iv;
   private Matrix matrix = new Matrix();
   private float scale = 1f;
   private ScaleGestureDetector SGD;
   
   @Override
   protected void onCreate(Bundle savedInstanceState) {
      super.onCreate(savedInstanceState);
      setContentView(R.layout.activity_main);
      
      iv=(ImageView)findViewById(R.id.imageView);
      SGD = new ScaleGestureDetector(this,new ScaleListener());
   }
   
   public boolean onTouchEvent(MotionEvent ev) {
      SGD.onTouchEvent(ev);
      return true;
   }
   
   private class ScaleListener extends ScaleGestureDetector.
   
   SimpleOnScaleGestureListener {
      @Override
      public boolean onScale(ScaleGestureDetector detector) {
         scale *= detector.getScaleFactor();
         scale = Math.max(0.1f, Math.min(scale, 5.0f));
         
         matrix.setScale(scale, scale);
         iv.setImageMatrix(matrix);
         return true;
      }
   }
   
   @Override
   public boolean onCreateOptionsMenu(Menu menu) {
      // Inflate the menu; this adds items to the action bar if it is present.
      getMenuInflater().inflate(R.menu.menu_main, menu);
      return true;
   }
   
   @Override
   public boolean onOptionsItemSelected(MenuItem item) {
      // Handle action bar item clicks here. The action bar will
      // automatically handle clicks on the Home/Up button, so long
      // as you specify a parent activity in AndroidManifest.xml.
      
      int id = item.getItemId();
      
      //noinspection SimplifiableIfStatement
      if (id == R.id.action_settings) {
         return true;
      }
      return super.onOptionsItemSelected(item);
   }
}

Bạn sửa đổi nội dung của res/layout/activity_main.xml.


   
   
      
   
      
   
      

Và đây là nội dung của res/values/string.xml.


   Hello world!
   Settings

Tiếp theo là nội dung của AndroidManifest.xml file.


   
      
      
         
         
            
            
         
         
      
   
   

Chạy ứng dụng Android vừa tạo ở trên.

Gesture trong Android

Chọn thiết bị mobile sẽ hiển thị màn hình mặc định là: −

Gesture trong Android

Bây giờ đặt hai ngón tay qua màn hình và sau đó di chuyển hai ngón tay sang hai bên, bạn sẽ thấy hình ảnh đang được phóng to hay thu nhỏ tùy theo cách bạn di chuyển. Hình dưới minh họa trường hợp phóng to. −

Gesture trong Android

Hình sau minh họa trường hợp thu nhỏ. −

Gesture trong Android