Get the x and y coordinates of a button in android?

I have been working on Android for some time and would like to know if it is possible to get the button position in android.

My goal is to get the X and Y coordinates and print them on LOGCAT.

Some kind of example to show me how to evaluate.

thanks

+6
source share
3 answers

Of course, you can get them, make sure that the views are drawn at least once before trying to get positions. You can try to get positions in onResume () and try these functions

view.getLocationInWindow() or view.getLocationOnScreen() 

or if you need something regarding a parent, use

 view.getLeft(), view.getTop() 

Links to API definitions:

+9
source

Like Azlam , you can use View.getLocationInWindow () to get the x, y coordinates .

Here is an example:

 Button button = (Button) findViewById(R.id.yourButtonId); Point point = getPointOfView(button); Log.d(TAG, "view point x,y (" + point.x + ", " + point.y + ")"); private Point getPointOfView(View view) { int[] location = new int[2]; view.getLocationInWindow(location); return new Point(location[0], location[1]); } 

Bonus To get the center point of a given view:

 Point centerPoint = getCenterPointOfView(button); Log.d(TAG, "view center point x,y (" + centerPoint.x + ", " + centerPoint.y + ")"); private Point getCenterPointOfView(View view) { int[] location = new int[2]; view.getLocationInWindow(location); int x = location[0] + view.getWidth() / 2; int y = location[1] + view.getHeight() / 2; return new Point(x, y); } 

I hope this example can be useful to someone.

+4
source
 buttonObj.getX(); buttonObj.getY(); 
0
source

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


All Articles