简体   繁体   中英

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

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)?

the method you use expect integer values as references of R.string.whatever . Cast the getTop() return value to String should work.

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

To get the x/y of the button (since API 11):

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

Doc :

The visual x position of this view, in pixels.

For API below 11 you are on the right way: getTop() is the equivalent of getY() but without a possible animation/translation. getLeft() is the quivalent of getX() with the same restriction.

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.

Try to use button1.getTop() + "" to change to a string.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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