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

Discussion in 'Android Questions' started by Dave O, May 23, 2015.

  1. Dave O

    Dave O Active Member Licensed 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?

  2. LucaMs

    LucaMs Expert Licensed 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.

    Sub GetParent(v As ViewAs Object
    Dim jobj = v As JavaObject
    Return jobj.RunMethod("getParent"Null)
    End Sub
  3. Dave O

    Dave O Active Member Licensed User

    The Java call is:
    int leftTop[] = new int[2];
    My attempt to do this in B4A is:
    Dim leftTop(2As Int
    Dim JO As JavaObject = aView
    "getLocationOnScreen"Array As Object(leftTop))
    viewLeft = leftTop(
    viewTop = leftTop(
    ...but no matter which view I feed it (aView), it always returns 0, 33.

    Any thoughts on what I'm doing wrong?

  4. LucaMs

    LucaMs Expert Licensed User

    It works!

    Attached Files:

    Beja, Dave O, Melghost and 1 other person like this.
  5. Melghost

    Melghost Member Licensed User

    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:
    Dave O, LucaMs and DonManfred like this.
  6. Dave O

    Dave O Active Member Licensed User

    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.

  1. This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
    By continuing to use this site, you are consenting to our use of cookies.
    Dismiss Notice