Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Android

วิธีจัดการ Swipe Gesture ขวา-ซ้าย ใน Android

ตัวอย่างนี้สาธิตวิธี จัดการ Swipe Gesture (ขวา-ซ้าย, บน-ล่าง) ใน Android

ขั้นตอนที่ 1: สร้างโปรเจกต์ใหม่ใน Android Studio

ไปที่ File → New Project และกรอกรายละเอียดที่จำเป็นทั้งหมด

ขั้นตอนที่ 2: เพิ่มโค้ดใน res/layout/activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:gravity="center"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:orientation="vertical">
    <Button
        android:id="@+id/swap"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentTop="true"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="27dp"
        android:text="Swipe here" />
</LinearLayout>

ใช้ Button เป็นพื้นที่รับ Swipe Gesture

ขั้นตอนที่ 3: เพิ่มโค้ดใน src/MainActivity.java

package com.example.myapplication;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        Button swipeButton = findViewById(R.id.swap);
        swipeButton.setOnTouchListener(new OnSwipeTouchListener(MainActivity.this) {
            @Override
            public void onSwipeTop() {
                Toast.makeText(MainActivity.this, "Swipe Up", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSwipeRight() {
                Toast.makeText(MainActivity.this, "Swipe Right", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSwipeLeft() {
                Toast.makeText(MainActivity.this, "Swipe Left", Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onSwipeBottom() {
                Toast.makeText(MainActivity.this, "Swipe Down", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

ขั้นตอนที่ 4: สร้าง OnSwipeTouchListener.java (Core Logic)

package com.example.myapplication;

import android.content.Context;
import android.view.GestureDetector;
import android.view.GestureDetector.SimpleOnGestureListener;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;

public class OnSwipeTouchListener implements OnTouchListener {
    private final GestureDetector gestureDetector;

    public OnSwipeTouchListener(Context ctx) {
        gestureDetector = new GestureDetector(ctx, new GestureListener());
    }

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

    private final class GestureListener extends SimpleOnGestureListener {
        private static final int SWIPE_THRESHOLD = 100; // px
        private static final int SWIPE_VELOCITY_THRESHOLD = 100; // px/sec

        @Override
        public boolean onDown(MotionEvent e) {
            return true; // ต้อง return true เพื่อรับ Event ต่อ
        }

        @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();

                // Horizontal Swipe มากกว่า Vertical
                if (Math.abs(diffX) > Math.abs(diffY)) {
                    if (Math.abs(diffX) > SWIPE_THRESHOLD && Math.abs(velocityX) > SWIPE_VELOCITY_THRESHOLD) {
                        if (diffX > 0) {
                            onSwipeRight(); // Swipe Right (ซ้ายไปขวา)
                        } else {
                            onSwipeLeft();  // Swipe Left (ขวาไปซ้าย)
                        }
                        result = true;
                    }
                }
                // Vertical Swipe มากกว่า Horizontal
                else if (Math.abs(diffY) > SWIPE_THRESHOLD && Math.abs(velocityY) > SWIPE_VELOCITY_THRESHOLD) {
                    if (diffY > 0) {
                        onSwipeBottom(); // Swipe Down (บนลงล่าง)
                    } else {
                        onSwipeTop();    // Swipe Up (ล่างขึ้นบน)
                    }
                    result = true;
                }
            } catch (Exception exception) {
                exception.printStackTrace();
            }
            return result;
        }
    }

    // Override ใน Activity/Fragment
    public void onSwipeRight() {}
    public void onSwipeLeft() {}
    public void onSwipeTop() {}
    public void onSwipeBottom() {}
}

การทดสอบแอปพลิเคชัน

รันแอปพลิเคชันบนอุปกรณ์ Android จริง ใน Android Studio คลิกไอคอน Run เลือกอุปกรณ์ แล้วตรวจสอบหน้าจอเริ่มต้น

วิธีจัดการ Swipe Gesture ขวา-ซ้าย ใน Android

Swipe บนปุ่ม จะแสดง Toast ตามทิศทาง

วิธีจัดการ Swipe Gesture ขวา-ซ้าย ใน Android

วิธีจัดการ Swipe Gesture ขวา-ซ้าย ใน Android

คำอธิบาย GestureDetector & SimpleOnGestureListener

  • GestureDetector - Class หลักตรวจจับ Gesture (Tap, Double Tap, Scroll, Fling, Long Press)
  • SimpleOnGestureListener - Base Class มี Implementation ว่าง ทำให้ Override เฉพาะที่ต้องการ
  • onDown() - ต้อง Return true เพื่อบอกว่า Consume Event นี้ (จะได้รับ Fling ต่อ)
  • onFling(e1, e2, velocityX, velocityY) - เรียกเมื่อมี Fling (Swipe Veloctiy สูง)

พารามิเตอร์สำคัญ

  • SWIPE_THRESHOLD - ระยะทางขั้นต่ำ (Pixel) เพื่อถือว่าเป็น Swipe (ปรับตามหน้าจอ: dp → px)
  • SWIPE_VELOCITY_THRESHOLD - ความเร็วขั้นต่ำ (px/sec) กันการ Tap ช้าๆ ถูกนับเป็น Swipe

ปรับแต่งสำหรับหน้าจอความหนาแน่นต่างๆ (Density Independent)

// แปลง dp เป็น px
float density = context.getResources().getDisplayMetrics().density;
int swipeThreshold = (int) (100 * density); // 100 dp
int velocityThreshold = (int) (100 * density);

ทางเลือกทันสมัย: ItemTouchHelper (สำหรับ RecyclerView)

หากต้องการ Swipe ใน RecyclerView (เช่น Swipe to Delete, Archive) ให้ใช้ ItemTouchHelper:

ItemTouchHelper.SimpleCallback callback = new ItemTouchHelper.SimpleCallback(0, ItemTouchHelper.LEFT | ItemTouchHelper.RIGHT) {
    @Override
    public boolean onMove(@NonNull RecyclerView rv, @NonNull ViewHolder vh, @NonNull ViewHolder target) {
        return false;
    }

    @Override
    public void onSwiped(@NonNull ViewHolder vh, int direction) {
        int position = vh.getBindingAdapterPosition();
        if (direction == ItemTouchHelper.LEFT) {
            // Swipe Left Action
        } else {
            // Swipe Right Action
        }
        adapter.notifyItemRemoved(position);
    }

    @Override
    public void onChildDraw(Canvas c, RecyclerView rv, ViewHolder vh, float dX, float dY, int actionState, boolean isCurrentlyActive) {
        // Custom Swipe Background (Icon, Color)
        super.onChildDraw(c, rv, vh, dX, dY, actionState, isCurrentlyActive);
    }
};
new ItemTouchHelper(callback).attachToRecyclerView(recyclerView);

กรณีใช้งาน Swipe Gesture

  • Navigation (ViewPager, Bottom Sheet)
  • Action บน List Item (Delete, Archive, Share)
  • Game Controls
  • Image Gallery (Next/Previous)
  • Pull to Refresh (Vertical Swipe Down)