2015-12-18 28 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

相关问题