B4J Code Snippet GetScreenPosition

Hi,

This snippet gives you the screen position of a node in your application. Useful when you have a pop-up that needs to be aligned to a control, like a tooltip for example.

B4X:
'Returns a map containing the x and y screen position values
'for the given node. If coordinates are not found, then return 0
'
'Example:
'Dim ScreenPos As Map = GetScreenPosition(MyNode)
'ScreenPos.Get("x")
'ScreenPos.Get("y")
Private Sub GetScreenPosition(n As Node) As Map
    Dim m As Map = CreateMap("x": 0, "y": 0)
    Dim x = 0, y = 0 As Double
    Dim joNode = n, joScene, joStage As JavaObject
  
    'Get the scene position:
    joScene = joNode.RunMethod("getScene",Null)
    If joScene.IsInitialized = False Then Return m
    x = x + joScene.RunMethod("getX", Null)
    y = y + joScene.RunMethod("getY", Null)

    'Get the stage position:
    joStage = joScene.RunMethod("getWindow", Null)
    If joStage.IsInitialized = False Then Return m
    x = x + joStage.RunMethod("getX", Null)
    y = y + joStage.RunMethod("getY", Null)
  
    'Get the node position in the scene:
    Do While True
        y = y + joNode.RunMethod("getLayoutY", Null)
        x = x + joNode.RunMethod("getLayoutX", Null)
        joNode = joNode.RunMethod("getParent", Null)
        If joNode.IsInitialized = False Then Exit
    Loop

    m.Put("x", x)
    m.Put("y", y)
    Return m
End Sub

Enjoy!
 
Last edited:

rwblinn

Well-Known Member
Licensed User
Longtime User
Hi,

thanks a lot - good.
Small hint on defining the map m is to use CreateMap instead:
B4X:
Dim m As Map = CreateMap("x":0, "y":0)
 

jmon

Well-Known Member
Licensed User
Longtime User
Hi,

thanks a lot - good.
Small hint on defining the map m is to use CreateMap instead:
B4X:
Dim m As Map = CreateMap("x":0, "y":0)
Thanks,

I totally forgot this function! I think I have seen that somewhere, but didn't pay attention to it. Thanks for the reminder!

By the way, I forgot to mention that this snippet works with child windows too, and child of child of child ...

Thank you.
 

jmon

Well-Known Member
Licensed User
Longtime User
Top