question

njsokalski avatar image
0 Votes"
njsokalski asked ·

Getting Location of View Relative to Screen & Page

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.

dotnet-android
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

njsokalski avatar image
0 Votes"
njsokalski answered ·

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

 int[] loc = { 0, 0 };
 Rect r = new Rect();
 myview.GetLocationOnScreen(loc);
 myview.GetWindowVisibleDisplayFrame(r);
 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.

·
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.

JarvanZhang-MSFT avatar image
0 Votes"
JarvanZhang-MSFT answered ·

Hello,​

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;
    else
        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.


·
10 |1000 characters needed characters left characters exceeded

Up to 10 attachments (including images) can be used with a maximum of 3.0 MiB each and 30.0 MiB total.