Getting Location of View Relative to Screen & Page

Nathan Sokalski 4,126 Reputation points

I have a View for which I need to know the X/Y position relative to the page or root layout. To get the position relative to the screen, I can use View.GetLocationOnScreen, but this includes the title bar. I need to know either the height of the title bar or the position relative to the root layout (in my case a GridLayout). Is there any easy way to do this? Thanks.

A Microsoft open-source app platform for building Android and iOS apps with .NET and C#.
5,325 questions
0 comments No comments
{count} votes

Accepted answer
  1. Nathan Sokalski 4,126 Reputation points

    I think I may have found a solution that usually works:

    int[] loc = { 0, 0 };
    Rect r = new Rect();
    loc[0] -= r.Left;
    loc[1] -= r.Top;

    The last 2 lines adjust loc to be relative to the window. I do not know if my code is the best way to do this, or if it will work for all scenarios, or even if it is completely appropriate, but it seems to work for now for me, so hopefully it can help everyone else too.

    0 comments No comments

1 additional answer

Sort by: Most helpful
  1. JarvanZhang 23,951 Reputation points


    Welcome to our Microsoft Q&A platform!

    I need to know either the height of the title bar or the position relative to the root layout

    Try using the property like View.Top to get the position recursively. Check the code:

       Button button = FindViewById<Button>(Resource.Id.button1);  
       LinearLayout layout = FindViewById<LinearLayout>(Resource.Id.layout);//get the layout of the xaml page, the layout should be the GridLayout in your case  
       var button_y = GetRelativeTop(button);  
       private int GetRelativeTop(View view)  
           if (view.Parent == layout)  
               return view.Top;  
               return view.Top + GetRelativeTop((View)view.Parent);  

    Best Regards,

    Jarvan Zhang

    If the response is helpful, please click "Accept Answer" and upvote it.

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    0 comments No comments