Reputation: 304
In Xamarin Forms if i create a simple view, like a BoxView
and I place into an AbsoluteLayout
with the proper AbsoluteLayout.SetLayoutBounds
and AbsoluteLayout.SetLayoutFlags
, then if I try to retrieve the box coordinates with box.X; box.Y, box.Width, box.Height
in Android they result null, 0,0,-1,-1. In iOS they are returned correctly.
Code example
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"
}
}
Upvotes: 0
Views: 97
Reputation: 15021
You could try to overriding the OnSizeAllocated
method :
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}");
}
or add SizeChanged
event to your box :
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}");
}
Upvotes: 1