简体   繁体   English

如何在android中获取视图的x,y坐标?

[英]How to get the x,y coordinates of a view in android?

I have used the following code to get the Location (x,y) coordinates of a view in my layout.I have a button and the following code to get its location on the scren.However it force closes the app when using this code.Also note that this statement has been called after setContentView().Following is the code 我已经使用以下代码来获取布局中视图的位置(x,y)坐标。我有一个按钮和以下代码来获取它在scren上的位置。但是当它使用此代码时强制关闭应用程序。另请注意,此语句已在setContentView()之后调用。以下是代码

Toast.makeText(MainActivity.this, button1.getTop(),Toast.LENGTH_LONG).show();

And following is the Error: 以下是错误:

 E/AndroidRuntime(11630): android.content.res.Resources$NotFoundException: String resource ID #0x196

.How do i get the view's (say a Button in my case) location on the screen(x,y coordinates)? 。如何在屏幕上显示视图(例如我的情况下是一个按钮)(x,y坐标)?

the method you use expect integer values as references of R.string.whatever . 您使用的方法期望整数值作为R.string.whatever引用。 Cast the getTop() return value to String should work. 将getTop()返回值转换为String应该可以工作。

Toast.makeText(MainActivity.this, String.valueOf(button1.getTop()), Toast.LENGTH_LONG).show();

To get the x/y of the button (since API 11): 获取按钮的x / y(自API 11起):

Toast.makeText(MainActivity.this, (int)button1.getX() + ":" + (int)button1.getY(), Toast.LENGTH_LONG).show();

Doc : Doc

The visual x position of this view, in pixels. 此视图的可视x位置(以像素为单位)。

For API below 11 you are on the right way: getTop() is the equivalent of getY() but without a possible animation/translation. 对于低于11的API,你的方法是正确的: getTop()相当于getY()但没有可能的动画/翻译。 getLeft() is the quivalent of getX() with the same restriction. getLeft()是具有相同限制的getX() getLeft()物。

button1.getTop() returns a int number, Toast.makeText() treat that int number as a string resource id which is not existed in fact, so it crashes. button1.getTop()返回一个int号, Toast.makeText()将该int号视为字符串资源id,实际上并不存在,因此它崩溃了。

Try to use button1.getTop() + "" to change to a string. 尝试使用button1.getTop() + ""更改为字符串。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM