Search code examples
c#xamarin.formslandscape-portraitscreen-rotation

Why does extented layout on landscape mode shows half black screen in Xamarin Forms?


I have two Views and two content pages, in one I have them arrange vertically and it's shown when the device is on portrait mode, something like this:

enter image description here

<StackLayout>
            <Grid>
                <Grid.RowDefinitions>
                    <RowDefinition Height="*"/>
                    <RowDefinition Height="Auto"/>
                </Grid.RowDefinitions>

                <views:ScoresView Grid.Row="0"/>
                <views:CategoriesView Grid.Row="1"/>

            </Grid>
        </StackLayout>

And the other content page for landscape mode

<StackLayout>
        <Grid>
            <Grid.RowDefinitions>
                <RowDefinition Height="*"/>
            </Grid.RowDefinitions>
            <Grid.ColumnDefinitions>
                <ColumnDefinition Width="*"/>
                <ColumnDefinition Width="Auto"/>
            </Grid.ColumnDefinitions>

            <views:ScoresView Grid.Column="0"/>
            <views:CategoriesView Grid.Column="1"/>
        </Grid>
    </StackLayout>

I wanted it to look like this: enter image description here

but looks like this: enter image description here

This is how I'm calling one or the other when the rotation is shifted

protected override void OnSizeAllocated(double width, double height)
        {
            base.OnSizeAllocated(width, height);
            if (width > height)
            {
                //device is landscape
                App.Current.MainPage = new CategoriesLands();
            }
            else
            {
                //device is portrait (or square)
            }
        }

Solution

  • You could change the StackLayout StackOrientation property to achieve the effect.

    <StackLayout x:Name="outerStack">       
         <views:ScoresView HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand"/>
         <views:CategoriesView HorizontalOptions="FillAndExpand" VerticalOptions="FillAndExpand"/>
    </StackLayout>
    

    in the behind code:

    private double width;
    private double height;
    protected override void OnSizeAllocated(double width, double height)
        {
            base.OnSizeAllocated(width, height);
            if (width != this.width || height != this.height)
            {
                this.width = width;
                this.height = height;
                if (width > height)
                {
                    outerStack.Orientation = StackOrientation.Horizontal;
                }
                else
                {
                    outerStack.Orientation = StackOrientation.Vertical;
                }
            }
        }
    

    the more you could refer to this.