Android Question [solved] absolute coordinates of view using getLocationOnScreen?

Dave O

Well-Known Member
Licensed User
Longtime User
Hi all,

I'm trying to get the absolute coordinates of a view (that is, relative to the activity, not the view's parent object).

There's a Java method called getLocationOnScreen that does this, but I'm not sure how to call it from B4A. Mainly I'm having trouble with the parameter it wants (an array of 2 integers).

Anyone have a code snippet handy?

Thanks!
 

LucaMs

Expert
Licensed User
Longtime User
I don't know that Java method (someone will answer to you)
but you could use getParent (recursively, if necessary) and calculate the absolute position.

B4X:
Sub GetParent(v As View) As Object
    Dim jobj = v As JavaObject
    Return jobj.RunMethod("getParent", Null)
End Sub
 
Upvote 0

Dave O

Well-Known Member
Licensed User
Longtime User
The Java call is:
B4X:
int leftTop[] = new int[2];
aView.getLocationOnScreen(leftTop);

My attempt to do this in B4A is:
B4X:
Dim leftTop(2) As Int
Dim JO As JavaObject = aView
JO.RunMethod("getLocationOnScreen", Array As Object(leftTop))
viewLeft = leftTop(0)
viewTop = leftTop(1)

...but no matter which view I feed it (aView), it always returns 0, 33.

Any thoughts on what I'm doing wrong?

Thanks!
 
Upvote 0

Melghost

Member
Licensed User
Longtime User
...but no matter which view I feed it (aView), it always returns 0, 33.

Any thoughts on what I'm doing wrong?

Thanks!

Hi, Dave!
Maybe you've already found the solution.
I think you called getLocationOnScreen from Activity_Create, when the screen isn't painted yet.
Try to call it later by using a timer, or a button as LucaMs did.

Note that getLocationOnScreen returns absolute coordinates, without considering the notification bar height. If your app doesn't run on full screen, maybe you'll need to see this post:
https://www.b4x.com/android/forum/threads/notification-bar-height.13003/#post-73275
 
Upvote 0

Dave O

Well-Known Member
Licensed User
Longtime User
I think you called getLocationOnScreen from Activity_Create, when the screen isn't painted yet.
Try to call it later by using a timer, or a button as LucaMs did.

Actually, I was calling it from activity_resume, but I think you're right about the screen not being painted fully, because when I used a CallSubDelayed there, it worked properly.

Thanks!
 
Upvote 0
Top