Sach K
Sach K

Reputation: 743

Xamarin Forms fade out animation isn't working

I'm having difficulties with the FadeTo extension method. The fade out works, but when fading in, it does not animate, the view just appears. This happens on both iOS and Android. Here is my code:

private async System.Threading.Tasks.Task FadeTaskView(bool appear)
{
    if (appear)
    {
        await _Scroller.FadeTo(1, 250, Easing.Linear);
    }
    else
    {
        await _Scroller.FadeTo(0, 250, Easing.Linear);
    }
}

private async void OnCalendarDateChanged()
{
    await FadeTaskView(false);

    Tasks.Load(_TaskBackingStore.Where((t) =>
        t.Due.Date == CalendarDate.Date
    ));

    await FadeTaskView(true);
}

When I remove/comment out the Tasks.Load line the animations works fine.

Any ideas welcome.

As a workaround I have amended the code to look like the below. It seems to work smoothly but with a performance cost on iOS:

    private async void OnCalendarDateChanged()
    {
        var tasksToShow = _TaskBackingStore.Where((t) =>
            t.Due.Date == CalendarDate.Date
        ).ToArray();
        
        await FadeTaskView(false);

        Tasks.Load(tasksToShow);

        if(Device.RuntimePlatform == Device.iOS)
            await System.Threading.Tasks.Task.Delay(750);

        await FadeTaskView(true);
    }

Upvotes: 1

Views: 905

Answers (1)

Brandon Minnick
Brandon Minnick

Reputation: 15420

It's likely that you are running the animations on a background thread.

We can leverage Device.InvokeOnMainThreadAsync to ensure that animations are happening on the Main Thread (aka the UI Thread).

private System.Threading.Tasks.Task FadeTaskView(bool appear) => Device.InvokeOnMainThreadAsync(async () =>
{   
    if (appear)
    {
        await _Scroller.FadeTo(1, 250, Easing.Linear);
    }
    else
    {
        await _Scroller.FadeTo(0, 250, Easing.Linear);
    }
}

private async void OnCalendarDateChanged()
{
    await FadeTaskView(false);

    Tasks.Load(_TaskBackingStore.Where((t) =>
        t.Due.Date == CalendarDate.Date
    ));

    await FadeTaskView(true);
}

Upvotes: 1

Related Questions