c# - 在 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);
}
}
此代码在方向更改时加载正确的布局,但只要方向更改并出现在与此布局关联的所需页面之外,就会调用它。
解决方案
在Xamarin.Forms中,您有像LayoutChanged
and之类的事件SizeChanged
,只要页面的布局发生更改(这包括页面创建时间和方向更改时)就会触发,因此可能是一个很好的查看位置。
在@jgoldberger-MSFT 下面建议的文章中,Xamarin 的团队推荐使用SizeChanged
(阅读文章了解更多详细信息!)
Xamarin.Forms 不提供任何本机事件来通知您的应用共享代码中的方向更改。但是,当 Page 的宽度或高度发生更改时,会触发 Page 的 SizeChanged 事件。
在Xamarin.Forms的ContentPage中,您可以简单地设置(超级基本示例):
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中,您可能仍然可以使用类似的Handler:LayoutChange
class Class1 : PageRenderer
{
public Class1(Context context) : base(context)
{
LayoutChange += (s, a) =>
{
};
}
}
希望这是有用的...
推荐阅读
- php - 将带有 jquery ajax 文件的 dataForm 发送到 php 页面
- autodesk-forge - 如何使用 Forge Design Automation 从 RVT 文件中导出 DWG
- python - 从 email.message 中的字符串设置电子邮件内容?
- java - 哪一个更快/更好/内存效率更高?
- python - 如何在python中使用正则表达式用星号替换所有反斜杠
- corda - Kubernetes 上的 Corda
- excel - 仅关闭当前打开的 Excel 窗口
- sql - 根据另一列的数据将数据插入列
- python-3.x - 烧瓶测试无法通过 appcontext_pushed.connected_to 设置 flask.g
- typo3 - 如何从 Typo3 中的错误 500 恢复我的网站?