Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cách phát hiện hướng vuốt (swipe) trái/phải, lên/xuống trên Android

Giới thiệu

Bài viết hướng dẫn phát hiện cử chỉ vuốt (swipe gesture) 4 hướng: trái, phải, lên, xuống bằng GestureDetector và SimpleOnGestureListener.

Các bước thực hiện

Bước 1: Tạo dự án mới

Android Studio → File → New Project → Empty Activity.

Bước 2: Giao diện (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:id="@+id/relativeLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="16dp"
    tools:context=".MainActivity">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Vuốt để phát hiện sự kiện Swipe"
        android:textSize="24sp"
        android:textStyle="bold" />
</RelativeLayout>

Bước 3: Logic chính (src/MainActivity.java)

import androidx.appcompat.app.AppCompatActivity;
import android.content.Context;
import android.os.Bundle;
import android.view.GestureDetector;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    OnSwipeTouchListener onSwipeTouchListener;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        // Gán listener cho root view
        onSwipeTouchListener = new OnSwipeTouchListener(this, findViewById(R.id.relativeLayout));
    }

    // Lớp lắng nghe touch và chuyển đổi thành gesture
    public static class OnSwipeTouchListener implements View.OnTouchListener {
        private final GestureDetector gestureDetector;
        private Context context;

        OnSwipeTouchListener(Context ctx, View mainView) {
            gestureDetector = new GestureDetector(ctx, new GestureListener());
            mainView.setOnTouchListener(this);
            context = ctx;
        }

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return gestureDetector.onTouchEvent(event);
        }

        // Xử lý các gesture cụ thể
        private final class GestureListener extends GestureDetector.SimpleOnGestureListener {
            private static final int SWIPE_THRESHOLD = 100;
            private static final int SWIPE_VELOCITY_THRESHOLD = 100;

            @Override
            public boolean onDown(MotionEvent e) {
                return true; // Bắt buộc trả true để nhận các event tiếp theo
            }

            @Override
            public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
                boolean result = false;
                try {
                    float diffY = e2.getY() - e1.getY();
                    float diffX = e2.getX() - e1.getX();

                    // Xác định hướng chính: ngang hay dọc
                    if (Math.abs(diffX) > Math.abs(diffY)) {
                        // Vuốt ngang
                        if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                            if (diffX > 0) {
                                onSwipeRight();
                            } else {
                                onSwipeLeft();
                            }
                            result = true;
                        }
                    } else {
                        // Vuốt dọc
                        if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
                            if (diffY > 0) {
                                onSwipeBottom();
                            } else {
                                onSwipeTop();
                            }
                            result = true;
                        }
                    }
                } catch (Exception exception) {
                    exception.printStackTrace();
                }
                return result;
            }
        }

        // Các callback mặc định (có thể override khi sử dụng)
        void onSwipeRight() { Toast.makeText(context, "Vuốt phải", Toast.LENGTH_SHORT).show(); }
        void onSwipeLeft()  { Toast.makeText(context, "Vuốt trái", Toast.LENGTH_SHORT).show(); }
        void onSwipeTop()   { Toast.makeText(context, "Vuốt lên", Toast.LENGTH_SHORT).show(); }
        void onSwipeBottom(){ Toast.makeText(context, "Vuốt xuống", Toast.LENGTH_SHORT).show(); }
    }
}

Bước 4: Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android"
    package="app.com.sample">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Chạy ứng dụng

Kết nối thiết bị, nhấn Run. Vuốt trên màn hình theo 4 hướng để thấy Toast thông báo.

Cách phát hiện hướng vuốt (swipe) trái/phải, lên/xuống trên Android

Giải thích thuật toán

  1. onDown(): Trả về true để báo cho GestureDetector biết chúng ta quan tâm đến chuỗi event này
  2. onFling(): Được gọi khi người dùng vuốt nhanh (fling). Nhận 2 điểm (e1, e2) và vận tốc (velocityX, velocityY)
  3. Ngưỡng (Threshold):
    • SWIPE_THRESHOLD = 100px: Khoảng cách tối thiểu để coi là swipe
    • SWIPE_VELOCITY_THRESHOLD = 100px/s: Tốc độ tối thiểu
  4. So sánh |diffX| vs |diffY|: Xác định swipe ngang hay dọc chiếm ưu thế

Cách sử dụng linh hoạt (Interface)

Tốt hơn là định nghĩa interface để Activity/Fragment tự xử lý:

public interface OnSwipeListener {
    void onSwipeLeft();
    void onSwipeRight();
    void onSwipeTop();
    void onSwipeBottom();
}

// Trong OnSwipeTouchListener:
private OnSwipeListener listener;
public void setOnSwipeListener(OnSwipeListener listener) { this.listener = listener; }

// Khi phát hiện:
if (listener != null) listener.onSwipeRight();

Lưu ý

  • GestureDetector chỉ hoạt động tốt trên View có kích thước đủ lớn
  • Trên RecyclerView/ListView, swipe có thể xung đột với scroll → cân nhắc dùng ItemTouchHelper
  • Có thể dùng thư viện androidx.swiperefreshlayout cho pull-to-refresh