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

วิธีใช้ Action Move Event (การลาก/เลื่อน) ใน Android

ภาพรวม

ตัวอย่างนี้สาธิตการจับเหตุการณ์ MotionEvent.ACTION_MOVE ซึ่งเกิดขึ้นซ้ำๆ ขณะที่ผู้ใช้ลากนิ้วบนหน้าจอ ใช้สำหรับ Drag & Drop, Drawing, Swipe gestures, และ Custom scrolling

ขั้นตอนการสร้างโปรเจกต์

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

Android Studio → File → New Project → Empty Activity

ขั้นตอนที่ 2: Layout (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:layout_height="match_parent"
    android:orientation="vertical"
    android:gravity="center"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/actionEvent"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_marginTop="30dp"
        android:textSize="40sp"
        android:gravity="center"
        android:text="ลากที่นี่"
        android:background="#E3F2FD"
        android:padding="20dp" />

</LinearLayout>

ขั้นตอนที่ 3: โค้ดหลัก (src/MainActivity.java)

package com.example.myapplication;

import android.os.Build;
import android.os.Bundle;
import android.support.annotation.RequiresApi;
import android.support.v4.view.MotionEventCompat;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnTouchListener;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {

    TextView textView;

    @SuppressLint("ClickableViewAccessibility")
    @RequiresApi(api = Build.VERSION_CODES.N)
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        TextView actionEvent = findViewById(R.id.actionEvent);
        actionEvent.setText("Action Move Test");
        
        actionEvent.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int x = (int) event.getX();
                int y = (int) event.getY();
                int rawX = (int) event.getRawX();
                int rawY = (int) event.getRawY();
                
                int action = MotionEventCompat.getActionMasked(event);
                
                switch (action) {
                    case MotionEvent.ACTION_DOWN:
                        Log.i("TouchEvent", "DOWN at (" + x + ", " + y + ")");
                        actionEvent.setText("DOWN: (" + x + ", " + y + ")");
                        v.setBackgroundColor(0xFF4CAF50);
                        return true; // สำคัญ: ต้อง return true เพื่อรับ MOVE
                    
                    case MotionEvent.ACTION_MOVE:
                        // เกิดขึ้นหลายครั้งขณะลาก
                        actionEvent.setText("MOVE: (" + x + ", " + y + ")\nRaw: (" + rawX + ", " + rawY + ")");
                        // Toast.makeText(MainActivity.this, "Moving: (" + x + "," + y + ")", Toast.LENGTH_SHORT).show();
                        break;
                    
                    case MotionEvent.ACTION_UP:
                        Log.i("TouchEvent", "UP at (" + x + ", " + y + ")");
                        actionEvent.setText("UP: (" + x + ", " + y + ")");
                        v.setBackgroundColor(0xFF2196F3);
                        break;
                    
                    case MotionEvent.ACTION_CANCEL:
                        Log.i("TouchEvent", "CANCEL");
                        v.setBackgroundColor(0xFF2196F3);
                        break;
                }
                return true;
            }
        });
    }
}

ข้อมูลสำคัญใน MotionEvent (ACTION_MOVE)

เมธอดคำอธิบาย
getX(), getY()พิกัดสัมพัทธ์กับ View (0,0 = มุมซ้ายบนของ View)
getRawX(), getRawY()พิกัดสัมพัทธ์กับหน้าจอ (0,0 = มุมซ้ายบนของ Screen)
getPressure()แรงกด (0.0 - 1.0) หากฮาร์ดแวร์รองรับ
getSize()ขนาดพื้นที่สัมผัส หากรองรับ
getHistorySize()จำนวนจุดประวัติ (Batched events) สำหรับ High-frequency sampling
getHistoricalX(i), getHistoricalY(i)พิกัดในอดีต (Batch processing)

ประสิทธิภาพ: Batched Events (Historical Points)

Android อาจส่ง MOVE events หลายจุดในครั้งเดียว (Batching) เพื่อประหยัด Battery:

case MotionEvent.ACTION_MOVE:
    int historySize = event.getHistorySize();
    
    // ประมวลผลจุดปัจจุบัน
    processMove(event.getX(), event.getY());
    
    // ประมวลผลจุดในอดีต (Batch)
    for (int i = 0; i < historySize; i++) {
        float hx = event.getHistoricalX(i);
        float hy = event.getHistoricalY(i);
        processMove(hx, hy);
    }
    break;

กรณีการใช้งาน ACTION_MOVE

  • Drawing/Painting Apps: วาดเส้นต่อเนื่อง
  • Drag & Drop: ย้าย View, Reorder List (RecyclerView ItemTouchHelper)
  • Custom Scrolling: Horizontal panning, Zoomable ImageView
  • Games: Joystick ควบคุมตัวละคร, Aiming
  • Gesture Recognition: Swipe, Fling, Circle, Custom shapes
  • Range SeekBar: Dual thumb slider

ข้อควรระวัง

  • ต้อง return true ใน ACTION_DOWN ถึงจะได้รับ ACTION_MOVE
  • ACTION_MOVE เกิดขึ้น บ่อยมาก (60-200 Hz) → ไม่ควรทำ Heavy work ใน onTouch
  • ใช้ getHistorySize() เพื่อประมวลผล Batch ลด Overhead
  • Debounce/Throttle หากอัปเดต UI บ่อยเกินไป
  • Multi-touch: ใช้ getPointerId(index) และ findPointerIndex(id) เพื่อติดตามแต่ละนิ้ว

แนะนำ: ใช้ GestureDetector หรือ Library

สำหรับ Gesture ปกติ (Swipe, Fling, Double tap, Long press) ใช้ GestureDetector แทนการเขียนเอง

GestureDetector detector = new GestureDetector(this, new GestureDetector.SimpleOnGestureListener() {
    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float vX, float vY) {
        // จัดการ Swipe/Fling
        return true;
    }
});

view.setOnTouchListener((v, event) -> detector.onTouchEvent(event));