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

I used the following code to get the location coordinates of Location (x, y) in my layout. I have a button and the following code to get its location on scren.However, this forces the application to close when using this code. Also note that this statement is called after setContentView (). Below is the code

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

And the following error:

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

. How to get an idea (for example, a button in my case) on the screen (x, y coordinates)?

+4
source share
3 answers

the method you use expects integer values ​​as R.string.whatever references. Insert the return value of getTop () into a String.

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

To get x / y buttons (starting with 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 APIs below 11, you are on the right track: getTop() is the equivalent of getY() , but without possible animation / translation. getLeft() is an equivalent of getX() with the same restriction.

+4
source

button1.getTop() returns an int number, Toast.makeText() treats this int number as an identifier for a string resource that does not actually exist, therefore it fails.

Try using button1.getTop() + "" to change the line.

0
source

Condition: MyButton link exists

 AtomicInteger leftButton = new AtomicInteger(); myButton.getViewTreeObserver().addOnGlobalLayoutListener( () -> { if (leftButton.get() == 0) { leftSubtitle.set(myButton.getLeft()); //do something once you get the value.. } } ); 
0
source

Source: https://habr.com/ru/post/1490693/


All Articles