Search code examples
c#androidavaloniauiavalonia

In avalonia for android, how do i get the size of my view?


I have a simple application in Avalonia with a MainView (which is a UserControl automatically created by the template) and not much in it.

I can start it on the android emulator, and it works, but it doesn't seem to have a width. I added a log after the view gets loaded, but it seems that the width is somehow not calculated. I only get NaN.

public MainView()
{
    InitializeComponent();
    this.Loaded += this.MainView_Loaded;
}

private void MainView_Loaded(object? sender, Avalonia.Interactivity.RoutedEventArgs e)
{
    Debug.WriteLine($"{this.Width}");
}

Is there a way to force this calculation or read the Width properly for an android device ?

I also tried to execute platform-specific code to get the view width and write it somewhere, but i couldn't find an entry point from MainActivity.cs to execute code after the App gets created.


Solution

  • It seems that Width is not used at all when running on Android ?

    There is another property Bounds which does the same thing, just more annoying to use:

    private void MainView_PropertyChanged(object? sender, AvaloniaPropertyChangedEventArgs e)
    {
        switch (e.Property.Name)
        {
            case "Bounds":
                Debug.WriteLine($"{((Rect)e.NewValue!).Width};
                break;
        }
    }