Search code examples
xamarinscreen-orientation

handling page orientation change in Xamarin


When using Xamarin, what is the best or most accepted method of handling changes in orientation?

I have a carousel page which rotates through 5 content pages (the same page, just different text/images), in the content pages I have a 6 row grid, each row containing either an image, text or a button.

When changing from portrait to landscape I reset the size and padding of these within OnSizeAllocated. This seems to work randomly for 3 out of 5 content pages, the text in the other 2 will be out of position, and it's not always the same 3 that work either.

I'm guessing there's a better way to do this than manually resize things?

protected override void OnSizeAllocated(double width, double height)
        {
            base.OnSizeAllocated(width, height); //must be called
            if (this.width != width || this.height != height)
            {
                this.width = width;
                this.height = height;
                //reconfigure layout
                if (width > height)
                {
                    img.HeightRequest = 62.5;
                    img.WidthRequest = 62.5;
                    logo.HeightRequest = 52.5;
                    logo.WidthRequest = 142.27;
                    headerStack.Padding = new Thickness(0, -60, 0, 0);
                    txtStack.Padding = new Thickness(20, -60, 20, 0);
                    sIndicator.Padding = new Thickness(20, 0, 20, 100);
                    sButton.Padding = new Thickness(0, -40, 0, 0);
                }
                else
                {
                    img.WidthRequest = 250;
                    img.HeightRequest = 250;
                    logo.HeightRequest = 70;
                    logo.WidthRequest = 189.7;
                    headerStack.Padding = new Thickness(20, 40, 20, 0);
                    txtStack.Padding = new Thickness(20, 0, 20, 0);
                    sIndicator.Padding = new Thickness(20, 25, 20, 0);
                }
            }
        }

Solution

  • With a few tweaks to what I was setting I got this working just fine, would still be interested in other peoples' views on how they do it.