简体   繁体   中英

Reload XML Layout in Xamarin.Android on Orientation Change?

I am trying to create two different layouts for portrait and landscape mode in Xamarin for my Android app.

I have created a layout folder for portrait mode, and layout-land for landscape. When I open the specific page, the correct layout is loaded based on the device's orientation. However, when I change the orientation while the page is already open, the layout does not change and only rotates. I have tried overriding OnConfigurationChanged in the mainActivity , but I am unsure how to call and load the layout for only the desired page.

public override void OnConfigurationChanged(Android.Content.Res.Configuration newConfig) 
{
    base.OnConfigurationChanged(newConfig);
    if (newConfig.Orientation == Android.Content.Res.Orientation.Portrait) 
    {
        LayoutInflater li = (LayoutInflater) this.GetSystemService(Context.LayoutInflaterService);
        SetContentView(Resource.Layout.myLayout);
    } 
    else if (newConfig.Orientation == Android.Content.Res.Orientation.Landscape) 
    {
        SetContentView(Resource.Layout.myLayout);
    }
}

This code loads the correct layout on orientation change, but it is called anytime the orientation is changed and occurs outside of the desired page that this layout is associated with.

In Xamarin.Forms , you have events like LayoutChanged and SizeChanged , that fires whenever the Layout of a Page changes (this includes when the page is created, and when orientation changes), so might be a good place to look at.

In the article suggested below by @jgoldberger-MSFT, the team at Xamarin recommend the use of SizeChanged (read the article for further details!)

Xamarin.Forms does not offer any native events for notifying your app of orientation changes in shared code. However, the SizeChanged event of the Page fires when either the width or height of the Page changes.

Inside a ContentPage in Xamarin.Forms you can simply set (super basic example):

public MainPage()
{
    InitializeComponent();

    SizeChanged += (s,a) =>
    {
        if (this.Width > this.Height ) // or any flag that you use to check the current orientation!
            this.BackgroundColor = Color.Black;
        else
            this.BackgroundColor = Color.White;
    };
}

Update:

In Page Renderer in Android you might still be able to use the similar LayoutChange Handler :

class Class1 : PageRenderer
{

    public Class1(Context context) : base(context)
    {
        LayoutChange += (s, a) =>
        {

        };
    }
}

Hope this is useful...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM