Xamarin Forms:Android 上的视图坐标为空

Xamarin Forms: view coordinates null on Android

在 Xamarin Forms 中,如果我创建一个简单的视图,例如 BoxView,然后我将适当的 AbsoluteLayout.SetLayoutBoundsAbsoluteLayout.SetLayoutFlags 放入 AbsoluteLayout,那么如果我尝试在 Android 中检索带有 box.X; box.Y, box.Width, box.Height 的框坐标,结果为 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}");
    }