首页 > 解决方案 > Xamarin Forms:在 Android 上查看坐标为空

问题描述

在 Xamarin Forms 中,如果我创建一个简单的视图,比如 a并且我用正确的andBoxView放入 an中,那么如果我尝试在 Android 中检索框坐标,它们会导致 null、0、0、-1、-1。在 iOS 中,它们被正确返回。AbsoluteLayoutAbsoluteLayout.SetLayoutBoundsAbsoluteLayout.SetLayoutFlagsbox.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"

    }
}

标签: c#xamarinxamarin.formsviewcoordinates

解决方案


您可以尝试覆盖该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}");
    }

推荐阅读