Khalid Osama
Khalid Osama

Reputation: 29

how can i add a lot of children without freeze the app xamarin forms

in the view page - xaml code

 <ScrollView>
          <StackLayout Orientation="Vertical" x:Name="SL">
                    
          </StackLayout>
</ScrollView>

code behind

  public Page3()
    {
        InitializeComponent();
        InitAsync();
       
      
    }

  private async void InitAsync()
  {
            await Task.Run(() =>
            {
                Thread.Sleep(3000);

            });

            btn5.Text = "Task 1 Done";
            await Task.Run(() =>
            {
                Thread.Sleep(1000);
            });
            btn6.Text = "Task 2 Done";


            Button[] btn1 = new Button[2000];
          
            for(int i=0; i< btn1.Length; i++)
            {
                btn1[i] = new Button();
                btn1[i].HorizontalOptions = LayoutOptions.Fill;
                btn1[i].HeightRequest = 50;
                btn1[i].Text = i.ToString();

                SL.Children.Add(btn1[i]);

            }


  }

now the problem is that the app freez until the for loop add all buttons, how can i let the app not freez when this loop working? thank you.

Upvotes: 0

Views: 133

Answers (1)

Shubham Tyagi
Shubham Tyagi

Reputation: 838

Try this , it will not freeze your UI

Xaml

<StackLayout>
    <Button Text="Add Data" Clicked="Button_Clicked"/>
    <ListView x:Name="myListView">
        <ListView.ItemTemplate>
             <DataTemplate>
                 <ViewCell>
                     <Button Text="{Binding .}"/>
                 </ViewCell>
             </DataTemplate>
         </ListView.ItemTemplate>
     </ListView>
</StackLayout>

Code Behind

private ObservableCollection<string> longList = new ObservableCollection<string>();
public ObservableCollection<string> LongList { get => longList; set { longList = value; OnPropertyChanged(nameof(LongList)); } }
...
private void Button_Clicked(object sender, System.EventArgs e)
{
    Task.Run(() =>
    {
        for (int i = 0; i < 2000; i++)
        {
            LongList.Add(i.ToString());
        }
        Device.BeginInvokeOnMainThread(() =>
        {
            myListView.ItemsSource = LongList;
        });
    });
}

Upvotes: 1

Related Questions