c# - Xamarin Forms:在 Android 上查看坐标为空
问题描述
在 Xamarin Forms 中,如果我创建一个简单的视图,比如 a并且我用正确的andBoxView
放入 an中,那么如果我尝试在 Android 中检索框坐标,它们会导致 null、0、0、-1、-1。在 iOS 中,它们被正确返回。AbsoluteLayout
AbsoluteLayout.SetLayoutBounds
AbsoluteLayout.SetLayoutFlags
box.X; box.Y, box.Width, box.Height
代码示例
public partial class MainPage : ContentPage
{
BoxView box;
public MainPage()
{
InitializeComponent();
}
protected override void OnAppearing()
{
base.OnAppearing();
box = new BoxView
{
BackgroundColor = Color.Red,
};
AbsoluteLayout.SetLayoutBounds(box, new Rectangle(0.6, 0.6, 0.25, 0.25));
AbsoluteLayout.SetLayoutFlags(box, AbsoluteLayoutFlags.All);
absolutelayout.Children.Add(box);
Console.WriteLine($"Box coordinates: {box.X} {box.Y} {box.Width} {box.Height}");
//IN ANDROID (galaxy s9 emulator): "Box coordinates: 0 0 -1 -1"
//IN IOS (iPhone 11 emulator): "Box coordinates: 186 403 104 224"
}
}
解决方案
您可以尝试覆盖该OnSizeAllocated
方法:
protected override void OnAppearing()
{
base.OnAppearing();
box = new BoxView
{
BackgroundColor = Color.Red,
};
AbsoluteLayout.SetLayoutBounds(box, new Rectangle(0.6, 0.6, 0.25, 0.25));
AbsoluteLayout.SetLayoutFlags(box, AbsoluteLayoutFlags.All);
absolutelayout.Children.Add(box);
box.SizeChanged += Box_SizeChanged;
}
protected override void OnSizeAllocated(double width, double height)
{
base.OnSizeAllocated(width, height);
//get the box's location
Console.WriteLine($"Box coordinates:{box.X} {box.Y} {box.Width} {box.Height}");
}
或将SizeChanged
事件添加到您的框中:
protected override void OnAppearing()
{
base.OnAppearing();
box = new BoxView
{
BackgroundColor = Color.Red,
};
AbsoluteLayout.SetLayoutBounds(box, new Rectangle(0.6, 0.6, 0.25, 0.25));
AbsoluteLayout.SetLayoutFlags(box, AbsoluteLayoutFlags.All);
absolutelayout.Children.Add(box);
box.SizeChanged += Box_SizeChanged;
}
private void Box_SizeChanged(object sender, EventArgs e)
{
//you could get the box's location here
Console.WriteLine($"Box coordinates:{box.X} {box.Y} {box.Width} {box.Height}");
}
推荐阅读
- javascript - 如何使用 new Date() 获取 DD-MM-YY hh:mm a, en-US, +0100 格式
- postgresql - 数据库初始化发生在 docker-compose 中其他服务的启动之后
- python - 实现我制作成视频的 CNN+LSTM 模型时遇到问题
- c# - 有没有办法反序列化为 ExpandoObject 并在之后进行强类型化
- python - 如何隐藏 print() 或在某些情况下不执行
- android - React Native:错误无法安装应用程序。确保您已设置 Android 开发环境
- python - 我的 django 应用程序中的链式字段是空的。我正在使用 django 智能选择
- css - "display:inline-block" 显示不同于 "display:inline flow-root"
- android - 撰写中的条件导航,无需单击
- python - python-telegram-bot 是否实现了 contacts.getLocated()?