Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發 >> 進階開發

Android Launcher 取得桌面圖示左上角座標的方法

編輯:進階開發

在自訂 Android Launcher 或桌面容器開發中,若需要知道每個圖示在畫面上的位置,例如要繪製連線、做拖曳吸附或動畫對齊,最直接的方式是遍歷桌面容器中的子 View,再逐一取出座標。

核心概念

桌面通常是由一個 View 群組構成,每個圖示對應一個子 View。只要呼叫 getChildCount 取得子項數量,再用 getChildAt 取出物件,就能判斷其型別並讀取位置。getLeft 與 getTop 會回傳相對父容器的橫向與縱向座標。

範例程式

public int[][] getAllChildCoordinate() {
    int size = this.getChildCount();
    int[][] coordinates = new int[size][2];

    for (int i = 0; i != size; i++) {
        View child = this.getChildAt(i);
        if (child instanceof BubbleTextView) {
            BubbleTextView btv = (BubbleTextView) child;
            coordinates[i][0] = btv.getLeft();
            coordinates[i][1] = btv.getTop();
        }
    }
    return coordinates;
}

上述程式會把符合條件的圖示座標寫入二維陣列。若只想取得可見圖示,還可加上 visibility 判斷。此處的圖示範圍包含 padding 與圖片內容,也就是 BubbleTextView 可見區域的左上角。

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