BiSaM
BiSaM

Reputation: 293

How to use ActivityIndicator in an async method

I have created an ActivityIndicator

<AbsoluteLayout
        VerticalOptions="CenterAndExpand"
        HorizontalOptions="CenterAndExpand"
        Grid.Column="1"
        Grid.ColumnSpan="2"
        Grid.Row="1">
    <ActivityIndicator 
       x:Name="activity"  
       IsRunning="False"  
       IsEnabled="False"  
       IsVisible="False"  
       Color="#49c7AB"  
       BackgroundColor="Transparent"/>
</AbsoluteLayout>

and I have a button which has the following click void

async void IbtnEnglisch_Clicked(object sender, EventArgs e)
{
    activity.IsEnabled = true;
    activity.IsRunning = true;
    activity.IsVisible = true;

    //do some stuff
    await Navigation.PushAsync(new Auswahl());

    activity.IsEnabled = false;
    activity.IsRunning = false;
    activity.IsVisible = false;
}

The ActivityIndicator is not shown during my stuff gets loaded. But when I get back to my side, than I can see it (of course when it is not set to false at the end).

I have tried to do something like this:

      Device.BeginInvokeOnMainThread(async () =>
      {
           //do my stuff
           await Navigation.PushAsync(new Auswahl());
      });

But it is also not working.

Can someone please help me?

Upvotes: 1

Views: 740

Answers (1)

Junior Jiang
Junior Jiang

Reputation: 12723

From shared code , that will not work . Because all code will be called at the same time inside IbtnEnglisch_Clicked Button click method .

async void IbtnEnglisch_Clicked(object sender, EventArgs e)
{
    activity.IsEnabled = true;
    activity.IsRunning = true;
    activity.IsVisible = true;

    //do some stuff
    await Navigation.PushAsync(new Auswahl());

    activity.IsEnabled = false;
    activity.IsRunning = false;
    activity.IsVisible = false;
}

Have a try with Timer to deal with that , then it will work . When task be finished , it will navigate to next page and hide the ActivityIndicator .

Sample code :

private async void Button_Clicked(object sender, EventArgs e)
{

    activity.IsEnabled = true;
    activity.IsRunning = true;
    activity.IsVisible = true;


    // await method here do task method 
    // here monitor a taskCount to know whether task be finished
    int taskCount = 0;
    Device.StartTimer(TimeSpan.FromSeconds(1), () =>
    {
        // called every 1 second
        // do stuff here
        taskCount++;
        if (taskCount == 3)
        {
            Console.WriteLine("finish");
            Navigation.PushAsync(new ContentPage() { Title = "new page" });
            activity.IsEnabled = false;
            activity.IsRunning = false;
            activity.IsVisible = false;
            return false; // return true to repeat counting, false to stop timer
        }
        else
        {
            return true;
        }
    });
}

The effect :

enter image description here

Upvotes: 1

Related Questions