Android:6種方式讓你高效 & 正確地獲取View的座標位置。快來看看!

前言

獲取 View 座標在 Android 開發中非常常見。今天carson將詳細給大家講解 獲取 View 座標常用6種方式:

  1. getLeft()、getTop()、getRight()、getBottom()
  2. getX()、getY()、getRawX()、getRawY()
  3. getLocationOnScreen()
  4. getLocationInWindow()
  5. getGlobalVisibleRect()
  6. getLocalVisibleRect()

方式1:getLeft()、getTop()、getRight()、getBottom()

1. 應用場景

獲得 View 相對 父View 的座標

2. 使用

view.getLeft();
view.getTop();
view.getRight();
view.getBottom();

3. 具體描述

View的位置由4個頂點決定的(如下A、B、C、D)

 

View的頂點

4個頂點的位置描述分別由4個值決定:(請記住:View的位置是相對於父控件而言的

 


方式2:getX()、getY()、getRawX()、getRawY()

1. 應用場景

獲得點擊事件處 相對點擊控件 & 屏幕的座標

2. 使用

該方式是通過motionEvent獲取的

motionEvent event;

event.getX();       
event.getY();

event.getRawX();    
event.getRawY();

3. 具體介紹

 


方式3:getLocationInWindow()

1. 應用場景

獲取控件 相對 窗口Window 的位置

2. 具體使用

int[] location = new int[2];
view.getLocationInWindow(location);
int x = location[0]; // view距離window 左邊的距離(即x軸方向)
int y = location[1]; // view距離window 頂邊的距離(即y軸方向)

// 注:要在onWindowFocusChanged()裏獲取,即等window窗口發生變化後

3. 示意圖

 


方式4:getLocationOnScreen()

1. 應用場景

獲得 View 相對 屏幕 的絕對座標

2. 使用

int[] location = new int[2];
view.getLocationOnScreen(location);
int x = location[0]; // view距離 屏幕左邊的距離(即x軸方向)
int y = location[1]; // view距離 屏幕頂邊的距離(即y軸方向)

// 注:要在view.post(Runable)裏獲取,即等佈局變化後

3. 示意圖

 


方式5:getGlobalVisibleRect()

1. 應用場景

View可見部分 相對於 屏幕的座標。

2. 具體使用

Rect globalRect = new Rect();
view.getGlobalVisibleRect(globalRect);

globalRect.getLeft();
globalRect.getRight();
globalRect.getTop();
globalRect.getBottom();

3. 示意圖

 

方式6:getLocalVisibleRect()

1. 應用場景

View可見部分 相對於 自身View位置左上角的座標。

2. 具體使用

Rect localRect = new Rect();
view.getLocalVisibleRect(localRect);

localRect.getLeft();
localRect.getRight();
localRect.getTop();
localRect.getBottom();

3. 示意圖

 


總結

本文對Android獲取View座標位置的方式進行了全面講解,總結如下:

 

漫漫開發之路,我們只是其中的一小部分……只有不斷的學習、進階,纔是我們的出路!纔跟得上時代的進步!

今年年初我花一個月的時間收錄整理了一套知識體系,如果有想法深入的系統化的去學習的,可以私信我【學習】,我會把我收錄整理的資料都送給大家,幫助大家更快的進階。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章