2015-12-18 27 views
0

我正在寫一個方法,在按鈕上繪製一個佈局ontop。我的問題在於我在較低的API上創建的佈局的位置。在較新的我使用setX()setY()方法,但由於這是不工作的更低,我試圖設置佈局參數Android - Use of view.setX() and setY in api 8但我沒有得到我想要的結果。有了這個Android:替換setX()用於較低的API

int[] location = new int[2]; 
button.getLocationOnScreen(location); 
int x = location[0]; 
int y = location[1]; 
borderRelativeLayout.setX(x); 
borderRelativeLayout.setY(y); 
viewGroup.addView(borderRelativeLayout) 

我實現這一目標: correct position

,但如果我用這個代碼來支持較低API的

relativeLayoutparams.leftMargin = x; 
relativeLayoutparams.topMargin = y; 
viewGroup.addView(borderRelativeLayout, relativeLayoutparams); 

我得到這個結果:incorrect

任何幫助,將不勝感激。

回答

0

對於API 1:

int[] location = new int[2]; 
button.getLocationOnScreen(location); 
int x = location[0]; 
int y = location[1]; 
borderRelativeLayout.offsetLeftAndRight(x - borderRelativeLayout.getLeft()); 
borderRelativeLayout.offsetTopAndBottom(y - borderRelativeLayout.getTop()); 

編輯:
你考慮了預期的效果背景繪製?

+0

謝謝,但相對佈局的'setLeft'和'setTop'也需要api 11. 使用background drawable是什麼意思?你能更特別嗎? – Alex

+0

對不起,我沒有意識到這一點。你可以使用offsetLeftAndRight和offsetTopAndBottom。無論如何,那些可繪製的東西呢?您可以使用drawable設置邊框。 –

+0

我使用drawable在佈局上創建邊框。我正在使用佈局來做到這一點,而不是直接按鈕,因爲如果它是一個自定義的按鈕,我不想改變按鈕的樣式。我會嘗試你的方法與抵消現在。 更新:相同的結果。 – Alex

相關問題