Press ESC to close

Xamarin ListView Lazy Loading

Hello friends. In this article, we will talk about how to add data as the user descends without loading all of the data when using List View with Xamarin. This is a process that is used especially in all large applications. For example, you will see new posts or tweets as you scroll down in apps like Instagram, Twitter or Facebook. When the screen is turned on, it loads as you go down instead of loading all posts or tweets. Let’s do this with Xamarin.

First we need to do the design part. For this, we need to throw a ListView and an Activity Indicator to the screen. We will simply display the number in the ListView, and when the user shows the last number, he will see a wait icon. After waiting for 2 seconds, we will add 20 new numbers. Normally, these transactions should come from the service, but because we will do it in a simple way, we throw a Delay.

Another issue we need to pay attention to here is that we need to use a feature of List View. This is the ItemAppearing feature. This function is triggered when any item is seen in List View.

<?xml version="1.0" encoding="utf-8" ?>
<ContentPage xmlns="http://xamarin.com/schemas/2014/forms"
             xmlns:x="http://schemas.microsoft.com/winfx/2009/xaml"
             x:Class="XamLazyLoading.MainPage">
    <Grid HorizontalOptions="FillAndExpand"
          VerticalOptions="FillAndExpand">
        <ListView HorizontalOptions="FillAndExpand"
                  VerticalOptions="FillAndExpand"
                  x:Name="listView"
                  ItemsSource="{Binding .}"
                  ItemAppearing="ListView_ItemAppearing">
            <ListView.ItemTemplate>
                <DataTemplate>
                    <ViewCell>
                        <Grid>
                            <Label Text="{Binding Name}"
                                   HorizontalOptions="Center"
                                   HorizontalTextAlignment="Center"
                                   VerticalOptions="Center"
                                   VerticalTextAlignment="Center"
                                   TextColor="Black"/>
                        </Grid>
                    </ViewCell>
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
        <ActivityIndicator HorizontalOptions="Center"
                           VerticalOptions="Center"
                           HeightRequest="40"
                           WidthRequest="40"
                           x:Name="indicator"
                           BackgroundColor="Red"
                           IsRunning="True"/>
    </Grid>

</ContentPage>

In the cs part of our application, we first load 20 items. While loading, we load new items after showing a standby icon on the screen and waiting for 2 seconds. In the ListView’s function triggered when every item appears, we need to check whether it is the last item or not. If it is the last item, we add new items.

using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Xamarin.Forms;

namespace XamLazyLoading
{
    public partial class MainPage : ContentPage
    {
        int pageSize = 20;
        public ObservableCollection<FruitModel> fruitList;

        public MainPage()
        {
            InitializeComponent();
            fruitList = new ObservableCollection<FruitModel>();
            //this.BindingContext = this;
            listView.ItemsSource = fruitList;
            AddListItem();
        }

        async Task AddListItem()
        {
            indicator.IsVisible = true;
            await Task.Delay(2000);
            int listCount = fruitList.Count;
            for (int index = listCount; index < listCount + pageSize; index++)
            {
                fruitList.Add(new FruitModel
                {
                    Name = index.ToString()
                });
            }
            indicator.IsVisible = false;
        }

        void ListView_ItemAppearing(System.Object sender, Xamarin.Forms.ItemVisibilityEventArgs e)
        {
            var item = e.Item as FruitModel;
            if (item == fruitList[fruitList.Count - 1])
            {
                AddListItem();
            }
        }
    }

    public class FruitModel
    {
        public string Name { get; set; }
    }
}

The screen output of the application is as follows.

If you have questions, you can reach by e-mail or comment. Good work.

Leave a Reply

Your email address will not be published. Required fields are marked *