如何在Android中獲取檢視的絕對座標?


在進入示例之前,我們應該瞭解什麼是絕對座標。它表示檢視在視窗管理器上的絕對位置 (x,y)。此示例演示瞭如何獲取檢視的絕對座標。

步驟 1 − 在 Android Studio 中建立一個新專案,轉到檔案 ⇒ 新建專案,並填寫所有必需的詳細資訊以建立新專案。

步驟 2 − 將以下程式碼新增到 res/layout/activity_main.xml 中。

<?xml version = "1.0" encoding = "utf-8"?>
<RelativeLayout
   xmlns:android = "http://schemas.android.com/apk/res/android"
   xmlns:tools = "http://schemas.android.com/tools"
   android:layout_width = "match_parent"
   android:layout_height = "match_parent"
   android:padding = "16dp"
   tools:context = ".MainActivity"
   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>

在上面的 xml 中,我們提供了一個 TextView。當用戶點選 TextView 時,它將在 Toast 上顯示檢視的位置。

步驟 3 − 將以下程式碼新增到 src/MainActivity.java 中

package com.example.andy.myapplication;

import android.graphics.Point;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.TextureView;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

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(new View.OnClickListener() {
         @Override
         public void onClick(View v) {
            int[] location = new int[2];
            textView.getLocationOnScreen(location);
            Toast.makeText(MainActivity.this,"X axis is "+location[0] +"and Y axis is "+location[1],Toast.LENGTH_LONG).show();
         }
      });
   }
   public static Point getLocationOnScreen(View view) {
      int[] location = new int[2];
      view.getLocationOnScreen(location);
      return new Point(location[0], location[1]);
   }
}

在上面的程式碼中,當用戶點選 TextView 時,它將在螢幕上顯示絕對座標。讓我們嘗試執行您的應用程式。我假設您已將您的實際 Android 移動裝置連線到您的計算機。要從 Android Studio 執行應用程式,請開啟您的一個專案活動檔案,然後點選工具欄中的執行 圖示。選擇您的移動裝置作為選項,然後檢查您的移動裝置,它將顯示您的預設螢幕 -

以上結果是初始螢幕,當用戶點選 TextView 時,將顯示如下結果 -

點選這裡下載專案程式碼

更新於: 2019年7月30日

4K+ 瀏覽量

開啟你的職業生涯

透過完成課程獲得認證

立即開始
廣告