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

Lấy tọa độ tuyệt đối (x, y) của View trên màn hình trong Android

Khái niệm

Tọa độ tuyệt đối = vị trí (x, y) của View so với gốc màn hình (window manager), không phải so với parent.

Cách làm

Bước 1: Tạo project

Bước 2: Layout activity_main.xml

<RelativeLayout ... android:padding="16dp" android:background="#dde4dd">
    <TextView android:id="@+id/text" android:layout_marginLeft="100dp" android:layout_width="wrap_content" android:layout_height="wrap_content" android:text="Hello World!" />
</RelativeLayout>

Bước 3: MainActivity.java

public class MainActivity extends AppCompatActivity {
    TextView textView;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        textView = findViewById(R.id.text);
        textView.setOnClickListener(v -> {
            int[] location = new int[2];
            textView.getLocationOnScreen(location); // Lấy tọa độ tuyệt đối
            Toast.makeText(this, "X: " + location[0] + ", Y: " + location[1], Toast.LENGTH_LONG).show();
        });
    }

    // Helper method trả về Point
    public static Point getLocationOnScreen(View view) {
        int[] loc = new int[2];
        view.getLocationOnScreen(loc);
        return new Point(loc[0], loc[1]);
    }
}

Phương thức chính: view.getLocationOnScreen(int[] location) - điền tọa độ x, y vào mảng.

Kết quả

Màn hình ban đầu:

Lấy tọa độ tuyệt đối (x, y) của View trên màn hình trong Android

Click TextView → Toast hiển thị tọa độ X, Y:

Lấy tọa độ tuyệt đối (x, y) của View trên màn hình trong Android

Lưu ý

  • Khác với getLocationInWindow() (tọa độ trong window, trừ status bar).
  • Gọi sau khi layout hoàn tất (trong onClick, onWindowFocusChanged, hoặc view.post()).