2010-04-14 116 views
52

getLocationOnScreen()getLocationInWindow()的調用都會給我一個top/Y座標,約爲〜30px(狀態/通知欄的高度)太低。 left/X座標已死亡。座標不正確getLocationOnScreen/getLocationInWindow

正如我上面暗示的,我認爲區別是因爲狀態/通知欄......我可能是錯的。如果我可以確定通知欄的大小,我想我可以解決這個問題,但是我很難做到這一點。

任何幫助將不勝感激。

回答

76

我最終通過確定像這樣的狀態/通知欄的高度解決這一問題:

View globalView = ...; // the main view of my activity/application 

DisplayMetrics dm = new DisplayMetrics(); 
this.getWindowManager().getDefaultDisplay().getMetrics(dm); 
int topOffset = dm.heightPixels - globalView.getMeasuredHeight(); 

View tempView = ...; // the view you'd like to locate 
int[] loc = new int[2]; 
tempView.getLocationOnScreen(loc); 

final int y = loc[1] - topOffset; 
+0

這在常規配置下工作,但如果當SoftInput/Keyboard打開時活動調整'globalView'高度,那麼鍵盤高度也會計算爲'topOffset',這會導致'y'值錯誤。 – 2014-01-06 15:09:00

+7

'int [] locInWindow = new int [2]; globalView.getLocationInWindow(locInWindow); topOffset = locInWindow [1];'//通過獲得'globalView'的Y座標來計算'topOffset' – 2014-01-06 15:39:35

+1

爲我節省了很多時間,謝謝! – Justin 2014-07-18 17:36:39

5

我有同樣的問題,請嘗試使用

offset = myView.GetOffsetY(); 

,並通過該值,如調整ÿ座標

coordY -= offset; 

它提供了`` - 方法的類:

class MyView extends View { 

    public int GetOffsetY() { 
    int mOffset[] = new int[2]; 
    getLocationOnScreen(mOffset); 
    return mOffset[1]; 
    } 

} 
+0

我沒有看到 「getOffsetY()」。什麼類是一種方法? – nimph 2010-05-03 20:55:19

+0

對不起,我無法發佈方法中,在 類MyView的延伸查看 { \t公衆詮釋GetOffsetY() \t { INT M偏移[] =新INT [2]; \t \t getLocationOnScreen(mOffset); \t \t return mOffset [1]; \t} – user330844 2010-07-13 14:17:19

5

這裏是我如何獲得狀態欄高度,並調整偏移量:

final int[] location = new int[2]; 
anchor.getLocationInWindow(location); // Includes offset from status bar, *dumb* 
Rect anchorRect = new Rect(location[0], location[1], 
     location[0] + anchor.getWidth(), location[1] + anchor.getHeight()); 

anchor.getRootView().findViewById(android.R.id.content).getLocationInWindow(location); 
int windowTopOffset = location[1]; 
anchorRect.offset(0, -windowTopOffset); 
+0

爲什麼窗口中的位置包含與狀態欄的偏移量?你要求在窗口中的位置*,那麼你還期望什麼? – 2013-06-29 22:47:09

+1

可以假定窗口在狀態欄下方,因此偏移量不包括狀態欄高度。 – satur9nine 2013-06-29 23:45:01

+0

你在混淆窗口和屏幕我認爲。 – 2013-07-16 00:55:28

4

此答案不包括如何獲取狀態欄高度,但它確實解釋了getLocationOnScreen()getLocationInWindow()返回相同值的行爲。

在正常活動(不是對話框)的情況下,您應該期望這兩種方法返回相同的值。一個窗口在下面(如z順序不是y座標)放置狀態欄,所以這些方法不能用來確定狀態欄的高度。

https://stackoverflow.com/a/20154562/777165

+0

對話框中的觀點,如果沒有設置窗口全屏是真的,但如果設置如下,它工作正常'topOffset' – iXcoder 2015-03-31 02:13:32