Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 取得控制元件在螢幕上的座標:三種 API 的差別

編輯:關於 Android 程式設計

做浮動提示、氣泡定位、動畫位移這類功能時,一定會遇到「這個 View 到底在螢幕的哪個位置」的問題。Android 提供了好幾組方法,但它們的參考原點各不相同,用錯就會出現莫名其妙的偏移。

範例程式

package xiaosi.location;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.ImageView;

public class LocationActivity extends Activity {

    private ImageView img = null;
    private Button button = null;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        img = (ImageView) findViewById(R.id.image);
        button = (Button) findViewById(R.id.button);
        button.setOnClickListener(new ButtonListener());
    }

    public class ButtonListener implements OnClickListener {
        public void onClick(View v) {
            int[] location = new int[2];
            img.getLocationOnScreen(location);
            int x = location[0];
            int y = location[1];

            System.out.println("x: " + x + "  y: " + y);
            System.out.println("Left:   " + img.getLeft());
            System.out.println("Right:  " + img.getRight());
            System.out.println("Top:    " + img.getTop());
            System.out.println("Bottom: " + img.getBottom());
        }
    }
}

對應的版面配置

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <Button
        android:id="@+id/button"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="button" />

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center"
        android:src="@drawable/a" />

</LinearLayout>

幾組方法的語意差異

getLocationOnScreen(int[] outLocation):回傳該 View 相對於整個螢幕左上角的座標。注意這個值包含了狀態列(通知列)的高度,也就是說它是從實體螢幕的最頂端算起。

getLocationInWindow(int[] outLocation):回傳該 View 相對於所處 Window 的座標。在多視窗或自訂 Dialog 情境下,這個值會與螢幕座標不同。

getLeft() / getTop() / getRight() / getBottom():這是一組相對於「直接父容器」的座標,回傳的是整數像素。它們在 onCreate() 階段全為 0,因為此時版面尚未配置。

還有一個容易混淆的 getGlobalVisibleRect() 與 getLocalVisibleRect(),前者算的是相對於螢幕的可見範圍,後者算的是相對於自身父容器的可見範圍,常用來判斷一個 View 是否真的被使用者看到。

實務提醒

座標取得必須在版面配置完成後進行。在 onCreate() 裡直接呼叫,幾乎都會拿到 0。可靠的做法有三種:把邏輯放進 View.post(Runnable)、註冊 ViewTreeObserver.OnGlobalLayoutListener,或等到使用者互動時才取(就像範例中的按鈕點擊)。

另外要留意螢幕旋轉與狀態列隱藏。旋轉後座標會全部改變,若你把座標快取下來 reuse,就會出現位置錯亂;而狀態列隱藏(全螢幕模式)會讓 getLocationOnScreen 的 y 值直接少掉一段,這也是很多「全螢幕後浮動元件跑位」問題的根源。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved