2014-01-08 52 views
2

我正在開發一個android鎖屏應用程序。我從另一個線程得到了想法,以檢查手指按下的位置與我設置的圖像按鈕的座標的座標。android .gettop()返回0.0

我想獲得使用.getTop().getLeft() imagebutton的座標,但都返回0.0(因爲它們是浮動,而不是int)。

這是爲什麼?我是新來的android開發,所以很抱歉,如果我失去了明顯的東西。

此外,我讀了一個地方,.getTop()將不會在setContentView(R.layout.layoutname)後工作,但如果我把它放在setContentView(...)以上,那麼應用程序崩潰。

是否有另一種獲得圖像按鈕座標的方法,還是獲得表格單元的座標和邊界會更好/更容易?我會怎麼做?

感謝提前:)

+0

[這](http://stackoverflow.com/questions/19932253/get-positions-of-views-in-a-dialog-relativ-to-their-parent/19933242#19933242)鏈路應該幫你。 – Naddy

回答

2
imagebutton.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED); 

imagebutton.getTop之前試試這個()?

+0

我得到這個錯誤:'類型不匹配:不能從void轉換爲浮點' – VaMoose

+0

'measure()'這被稱爲找出一個視圖應該有多大。父級在寬度和高度參數中提供約束信息。你應該在調用'getTop()'.clear之前調用度量? – venciallee

-1

這應該做的工作;)

// Your view 
ImageView image = (ImageView) findViewById(R.id.image); 

Rect rect = new Rect(); 
image;getLocalVisibleRect(rect); 
Log.d("WIDTH :",String.valueOf(rect.width())); 
Log.d("HEIGHT :",String.valueOf(rect.height())); 
Log.d("left :",String.valueOf(rect.left)); 
Log.d("right :",String.valueOf(rect.right)); 
Log.d("top :",String.valueOf(rect.top)); 
Log.d("bottom :",String.valueOf(rect.bottom));` 
+0

它們仍然會產生「0」。這將工作與imagebutton或只有imageview? – VaMoose

+0

它應該可以用於任何視圖。你之前把'setContentView'放進去了嗎? – Manitoba

+0

是的,我設置了'setContentView'之後的所有變量,或者它崩潰了 – VaMoose

3

你需要你的觀點加入到佈局並顯示(至少一個佈局傳遞和測量通必須運行)。此外,這樣獲得的座標是相對於視圖的直接父對象而言的。

It is possible to retrieve the location of a view by invoking the methods getLeft() and getTop(). The former returns the left, or X, coordinate of the rectangle representing the view. The latter returns the top, or Y, coordinate of the rectangle representing the view. These methods both return the location of the view relative to its parent. For instance, when getLeft() returns 20, that means the view is located 20 pixels to the right of the left edge of its direct parent.

+1

爲了確保視圖顯示調用onWindowFocusChanged(boolean hasFocus) – jos