C# Xamarin表单:Android上的视图坐标为空
在Xamarin表单中,如果我创建了一个简单的视图,比如C# Xamarin表单:Android上的视图坐标为空,c#,xamarin,xamarin.forms,view,coordinates,C#,Xamarin,Xamarin.forms,View,Coordinates,在Xamarin表单中,如果我创建了一个简单的视图,比如BoxView,并使用适当的AbsoluteLayout.SetLayoutBounds和AbsoluteLayout.SetLayoutFlags将其放入一个AbsoluteLayout中,那么如果我尝试使用box.X检索框坐标;box.Y,box.Width,box.Height在Android中,它们的结果为null,0,0,-1,-1。在iOS中,它们被正确返回 代码示例 public partial class MainPage
BoxView
,并使用适当的AbsoluteLayout.SetLayoutBounds
和AbsoluteLayout.SetLayoutFlags
将其放入一个AbsoluteLayout
中,那么如果我尝试使用box.X检索框坐标;box.Y,box.Width,box.Height
在Android中,它们的结果为null,0,0,-1,-1。在iOS中,它们被正确返回
代码示例
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}");
}
您无法获取x,y,因为元素尚未在屏幕上绘制。如果你能像Task.delay(2000)一样放置一个延迟,你会看到x,y。但这不是解决方案。@sermet它仍然不起作用,继续返回0和-1值,这很奇怪,因为在iOS中,即使不使用任何延迟也可以工作。尝试通过单击按钮来获取坐标。@Nikhileshwar这样做是可行的,但在我的项目中,当应用程序加载时,我需要它们。这是一个页面如何在每个平台上呈现自己的情况。您可能需要执行以下操作: