Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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

like image 832
Joyson Avatar asked Jul 10 '13 10:07

Joyson


People also ask

How to get xy coordinates of view in Android?

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

How do you find the X and Y coordinates on a screen?

Point Position (for Windows) is a simple tool that lets you pick the coordinates for any point on your screen (using X,Y axis). Simply point one of the four corner arrows at the spot on your screen that you want to define and click the button to display the X/Y coordinates.

How do I get touch coordinates on Android?

You can retrieve the coordinates by using getX() and getY() .


1 Answers

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.

like image 160
WarrenFaith Avatar answered Oct 21 '22 03:10

WarrenFaith