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

Android 依座標取得對應子 View 的實作

編輯:關於 Android 程式設計

有些互動場景(例如自繪的畫布、手勢分派、老祖宗留下的多層 ViewGroup 結構)需要反過來做一件事:給我一個螢幕座標,告訴我底下是哪個 View。做法是由外而內遞迴搜尋。

在 Activity 中使用

/**
 * 依座標取得對應的子 View(在 Activity 中使用)
 * @param x 座標
 * @param y 座標
 * @return 目標 View
 */
public View getViewAtActivity(int x, int y) {
    // 從 Activity 取得最上層容器
    View root = getWindow().getDecorView();
    return findViewByXY(root, x, y);
}

在自訂 ViewGroup 中使用

/**
 * 依座標取得對應的子 View(在自訂 ViewGroup 中使用)
 */
public View getViewAtViewGroup(int x, int y) {
    return findViewByXY(this, x, y);
}

核心遞迴邏輯

private View findViewByXY(View view, int x, int y) {
    View targetView = null;
    if (view instanceof ViewGroup) {
        // 是父容器,逐一遞迴搜尋子 View
        ViewGroup v = (ViewGroup) view;
        for (int i = 0; i < v.getChildCount(); i++) {
            targetView = findViewByXY(v.getChildAt(i), x, y);
            if (targetView != null) {
                break;
            }
        }
    } else {
        targetView = getTouchTarget(view, x, y);
    }
    return targetView;
}

private View getTouchTarget(View view, int x, int y) {
    View targetView = null;
    // 取出該 View 底下所有可接收觸控的子 View
    ArrayList<View> touchableViews = view.getTouchables();
    for (View child : touchableViews) {
        if (isTouchPointInView(child, x, y)) {
            targetView = child;
            break;
        }
    }
    return targetView;
}

private boolean isTouchPointInView(View view, int x, int y) {
    int[] location = new int[2];
    view.getLocationOnScreen(location);
    int left = location[0];
    int top = location[1];
    int right = left + view.getMeasuredWidth();
    int bottom = top + view.getMeasuredHeight();

    return view.isClickable()
            && y >= top && y <= bottom
            && x >= left && x <= right;
}

幾個實作上的提醒

  • getTouchables() 只會回傳「願意接收觸控」的子 View,因此像 TextView 這種不可點擊的元件預設不會被回傳。若需要涵蓋它們,可改用 ViewGroup.getChildAt 搭配座標判斷自行遞迴。
  • 座標系統要一致。這裡用 getLocationOnScreen,取得的是螢幕絕對座標;若你的輸入是相對某個父容器的座標,應改用 getLocationInWindow 或做相應的偏移換算。
  • getMeasuredWidth/Height 反映的是測量結果,在 layout 完成前呼叫可能拿到 0。請確認在 onLayout 之後或加上有效性檢查。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved