Petr Petr - 2 months ago 10
C# Question

How to display spinning wheel while going through all updating routines?

I'm currently working on some mobile project written on Xamarin.Forms. And I have a problem here. I need to update my listview containing some data. So I enabled

IsPullToRefreshEnabled = true
and

listView.Refreshing += (sender, e) => {
method1();

method2();

listView.EndRefresh();
};


However, I'm not sure, how to make spinning indicator showing until all updating routines are done.

public class Class1 : ContentPage
{
readonly Class2 manager = new Class2();
void BuildUI()
{
listView = new ListView
{
ItemsSource = new object[] { },
ItemTemplate = new DataTemplate(listRender.MakeCell),

RowHeight = 88,
HorizontalOptions = LayoutOptions.FillAndExpand,
VerticalOptions = LayoutOptions.FillAndExpand,

IsPullToRefreshEnabled = true,
IsRefreshing = false,
};

listView.Refreshing += (sender, e) =>
{
listView.IsRefreshing = true;

manager.ForceUpdate();

listView.IsRefreshing = false;
listView.EndRefresh();
};
}
}

public class Class2
{
public bool isUpdating = false;

public void ForceUpdate()
{
if (!running)
{
return;
}

if (!data.IsLoading)
{
isUpdating = true;
FetchUpdate();
isUpdating = false;
}
}
void FetchUpdate(Action oncomplete = null){/some code/}
}

Answer

Do you mean the PullToRefresh ActivityIndicator? For that you have to set the IsRefreshing property to true. So just set it to true at the beginning and to false whenever you're ready, like this.

listView.Refreshing += (sender, e) =>  { 
    listView.IsRefreshing = true;

    method1();

    method2();

    listView.IsRefreshing = false;
    listView.EndRefresh();
};

This will not work if the methods are async because it will go directly to the IsRefreshing = false.

There are multiple ways to go about this, run them sync, which is probably not what you want or create a public property which you bind to the listView.IsRefreshing property. And then set that property from the point where you are really done loading!

Update

As you provided your code, one way to go about this is like this:

  • Set your listView.IsRefreshing to pumpsManager.isLoading
  • Implement the INotifyPropertyChanged on your FuelPumpsDataManager and implement it on the isLoading. Note, you'll need to convert the 'isLoading' to a property. Another way to do this easier is by using the PropertyChanged.Fody NuGet package.

Now you can set the isLoading whenever it starts and stops loading and your ListView should show the animation accordingly.

Comments