首页 > 解决方案 > 在 Xamarin.Android 中重新加载 XML 布局以改变方向?

问题描述

我正在尝试为我的 Android 应用程序在 Xamarin 中为纵向和横向模式创建两种不同的布局。

我为纵向模式创建了一个布局文件夹,并为横向模式创建了 layout-land。当我打开特定页面时,会根据设备的方向加载正确的布局。但是,当我在页面已经打开时更改方向时,布局不会改变,只会旋转。我曾尝试OnConfigurationChanged在 中覆盖mainActivity,但我不确定如何仅为所需页面调用和加载布局。

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);
    }
}

此代码在方向更改时加载正确的布局,但只要方向更改并出现在与此布局关联的所需页面之外,就会调用它。

标签: c#androidxamarinxamarin.android

解决方案


Xamarin.Forms中,您有像LayoutChangedand之类的事件SizeChanged,只要页面的布局发生更改(这包括页面创建时间和方向更改时)就会触发,因此可能是一个很好的查看位置。

在@jgoldberger-MSFT 下面建议的文章中,Xamarin 的团队推荐使用SizeChanged(阅读文章了解更多详细信息!)

Xamarin.Forms 不提供任何本机事件来通知您的应用共享代码中的方向更改。但是,当 Page 的宽度或高度发生更改时,会触发 Page 的 SizeChanged 事件。

Xamarin.FormsContentPage中,您可以简单地设置(超级基本示例):

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;
    };
}

更新:

Android的Page Renderer中,您可能仍然可以使用类似的HandlerLayoutChange

class Class1 : PageRenderer
{

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

        };
    }
}

希望这是有用的...


推荐阅读