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

Cách lấy tọa độ chạm (touch position) trên màn hình Android?

Giới thiệu

Bài viết minh họa cách lấy tọa độ X, Y khi người dùng chạm vào màn hình thông qua OnTouchListener và MotionEvent.

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

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

Khởi tạo project Android Studio.

Bước 2: Giao diện hiển thị tọa độ (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:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="MainActivity">
    <EditText
        android:layout_width="400dp"
        android:layout_height="wrap_content"
        android:id="@+id/editText"
        android:hint="Tọa độ trục X" />
    <EditText
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/editText2"
        android:layout_below="@+id/editText"
        android:layout_alignLeft="@+id/editText"
        android:layout_alignStart="@+id/editText"
        android:hint="Tọa độ trục Y"
        android:layout_alignRight="@+id/editText"
        android:layout_alignEnd="@+id/editText" />
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Chạm để lấy tọa độ"
        android:id="@+id/textview"
        android:focusable="true"
        android:clickable="true"
        android:textSize="20dp"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />
</RelativeLayout>

Bước 3: Xử lý sự kiện chạm (src/MainActivity.java)

package app.com.sample;

import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    TextView T;
    EditText E1, E2;
    float x = 0f;
    float y = 0f;

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

        E1 = findViewById(R.id.editText);
        E2 = findViewById(R.id.editText2);
        T = findViewById(R.id.textview);

        T.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                final float x = event.getX();
                final float y = event.getY();

                float lastXAxis = x;
                float lastYAxis = y;

                E1.setText(Float.toString(lastXAxis));
                E2.setText(Float.toString(lastYAxis));

                return true; // Đã xử lý sự kiện
            }
        });
    }
}

Bước 4: AndroidManifest.xml

<?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: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. Chạm vào TextView "Chạm để lấy tọa độ", tọa độ X, Y sẽ hiển thị trong 2 EditText.

Cách lấy tọa độ chạm (touch position) trên màn hình Android?

Cách lấy tọa độ chạm (touch position) trên màn hình Android?

Giải thích quan trọng

  • event.getX(), event.getY(): Tọa độ tương đối so với View được chạm
  • event.getRawX(), event.getRawY(): Tọa độ tuyệt đối so với màn hình
  • event.getAction(): Loại hành động (DOWN, MOVE, UP, CANCEL)
  • Trả về true trong onTouch để nhận tiếp các sự kiện MOVE, UP

Ứng dụng thực tế

Kỹ thuật này dùng cho: vẽ chữ ký, kéo thả (drag & drop), game điều khiển bằng chạm, zoom/pan ảnh, v.v.