Giới thiệu
Ví dụ này minh họa cách xử lý sự kiện ACTION_MOVE (ngón tay di chuyển trên màn hình) để theo dõi tọa độ chạm.
Các bước thực hiện
Bước 1: Tạo dự án mới
Mở Android Studio, chọn File → New Project.
Bước 2: Thiết kế giao diện (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">
<TextView
android:id="@+id/actionEvent"
android:textSize="40sp"
android:layout_marginTop="30dp"
android:layout_width="wrap_content"
android:layout_height="match_parent" />
</LinearLayout>
Bước 3: Viết logic (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.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
@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");
actionEvent.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
int x = (int) event.getX();
int y = (int) event.getY();
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Log.i("TAG", "Chạm xuống");
break;
case MotionEvent.ACTION_MOVE:
Toast.makeText(MainActivity.this, "Đang di chuyển: (" + x + "," + y + ")", Toast.LENGTH_SHORT).show();
break;
case MotionEvent.ACTION_UP:
Log.i("TAG", "Nhấc lên");
break;
}
return true; // Quan trọng: trả về true để nhận tiếp ACTION_MOVE và ACTION_UP
}
});
}
}
Lưu ý: Phải trả về true trong ACTION_DOWN để hệ thống tiếp tục gửi ACTION_MOVE và ACTION_UP. Dùng Toast.LENGTH_SHORT tránh lag khi di chuyển nhanh.
Chạy ứng dụng
Chạy trên thiết bị thật. Vuốt ngón tay trên TextView sẽ hiển thị tọa độ (x,y) liên tục.
