Location, Insets & Orientation

Nathan Sokalski 4,116 Reputation points
2022-05-30T03:07:03.677+00:00

I need to get the X/Y location of several View(s). I am doing this using the GetLocationOnScreen, GetLocationInWindow & GetLocationInSurface methods (I wasn't sure what the difference was, since they seemed to be giving the same values). I am also getting the insets using the following code:

Android.Graphics.Insets squareinsets;
try { squareinsets = this.RootWindowInsets.GetInsets(WindowInsets.Type.SystemBars()); }
catch { squareinsets = this.RootWindowInsets.SystemWindowInsets; }

However, I seem to be having trouble getting it to respond correctly for all orientations. Resources.Configuration.Orientation only has values for Undefined, Portrait, Landscape, & Square. However, things like the insets are not the same when rotating to the left & right. My primary goal is to create a Rect for the View(s) involved (I am doing all this in the OnDraw of a custom view, and the View(s) for which I am trying to create the Rect(s) are not part of the custom view). How can I detect all orientations, and which of the GetLocation* methods should I be using?

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

Accepted answer
  1. Leon Lu (Shanghai Wicresoft Co,.Ltd.) 68,656 Reputation points Microsoft Vendor
    2022-05-31T09:51:36.943+00:00

    Hello,​

    Firstly, please ask one question at a time.

    things like the insets are not the same when rotating to the left & right.

    You can use SurfaceOrientation orientation = instance.WindowManager.DefaultDisplay.Rotation; to get the orientation .

    If you rotate to left, you will get orientation is Rotation90; If you rotate to right, you will get orientation is Rotation270

    Best Regards,

    Leon Lu


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment".

    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

0 additional answers

Sort by: Most helpful