繁体   English   中英

在方向更改时重新加载 Xamarin.Android 中的 XML 布局?

[英]Reload XML Layout in Xamarin.Android on Orientation Change?

我正在尝试为我的 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);
    }
}

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

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

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

更新:

AndroidPage Renderer中,您可能仍然可以使用类似的LayoutChange Handler

class Class1 : PageRenderer
{

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

        };
    }
}

希望这是有用的...

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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