Forum Xamarin Xamarin.Android

Add elements to a ListView on Button Click

I've searched a lot on this forum but i don't find an answer how i can add a new item to a list view on Button click?

Tagged:

Answers

  • jonathan_beckjonathan_beck USUniversity ✭✭✭

    Hi @FilippoBiondi

    The best option would be to update the list that the ArrayAdapter uses by working with the ArrayAdapter methods. Use the methods on the ArrayAdapter object. Add, Insert, Remove, Clear for example. This should dynamically update the list.

    You can also use OnNotifyDataSetChanged, but the best practice would be to use the ArrayAdapter's methods to update the list.

  • MabroukMabrouk USMember ✭✭✭

    Hi @FilippoBiondi

    1. If your list view name is : listView and shows a list of persons' names.
    2. Every item is like :
      public class Person { public string name {get;set;} }
    3. In your Button event :
      private void addPerson_click(object sender, EventArgs e) { Person person=new Person(){name="Mabrouk"}; // or get data from an other way... listView.ItemsSource.Add(person); }
    4. In your XAML page, you should have something like :
      <ListView x:Name="listView" VerticalOptions="FillAndExpand" SeparatorVisibility="None"> <ListView.ItemTemplate> <DataTemplate> <Label Text="{Binding name}" /> </DataTemplate> </ListView.ItemTemplate> </ListView>

    Hope that helps.

    Mabrouk.

  • jonathan_beckjonathan_beck USUniversity ✭✭✭

    If you are working in Xamarin.Forms, @Mabrouk has the correct answer. If you are working in Xamarin.Android, you'll need to work with the array adapter object.

  • MabroukMabrouk USMember ✭✭✭
    edited September 2016

    @JBeck , yes my answer was for Xamarin.Forms..
    But in xamarin.android, @FilippoBiondi needs to something like this :
    1. having a private List<Person> _persons=new List<Person>(); before,
    2. Add the new person to _persons in the button click event like :
    private void addPerson_click(object sender, EventArgs e) { Person person=new Person(){name="Mabrouk"}; // or get data from an other way... _persons.Add(person); ArrayAdapter adapter = new ArrayAdapter (this, Resource.Layout.TextViewItem, _persons); listView.Adapter=adapter; }
    3. Note : the code is not perfect ;) it will be better when you customize your Adapter..

  • jonathan_beckjonathan_beck USUniversity ✭✭✭
    edited September 2016

    Hi @Mabrouk

    Your code will work, but it will result in rebuilding the list every time the user clicks the add button, which is very inefficient.

    In the following code, the button click event adds the code to the Adapter's existing list. Note that I've added the ListViewItem.axml to the Resources/layout folder, with a TextView with ID label. I've attached a screenshot of it in action.

    MainActivity

    using System;
    using Android.App;
    using Android.Widget;
    using Android.OS;
    using System.Collections.Generic;
    
    namespace AndroidSandbox {
        [Activity(Label = "AndroidSandbox", MainLauncher = true, Icon = "@drawable/icon")]
        public class MainActivity : Activity {
    
            protected override void OnCreate(Bundle bundle) {
                base.OnCreate(bundle);
    
                // Set our view from the "main" layout resource
                SetContentView(Resource.Layout.Main);
    
                // Get our button from the layout resource,
                // and attach an event to it
                Button button = FindViewById<Button>(Resource.Id.MyButton);
                button.Click += addPerson_click;
    
                var listView = FindViewById<ListView>( Resource.Id.PeopleListView );
                listView.Adapter = new ArrayAdapter<string>(this, Resource.Layout.ListViewItem, Resource.Id.label);
            }
    
            private void addPerson_click(object sender, EventArgs e) {
                ArrayAdapter<string> adapter = (ArrayAdapter<string>)FindViewById<ListView>(Resource.Id.PeopleListView).Adapter;
                adapter.Add("New Person Name");
            }
        }
    }
    

    Main.axml

    <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <Button
            android:id="@+id/MyButton"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:text="Add Person" />
      <ListView
        android:id="@+id/PeopleListView" 
        android:layout_width="match_parent"
            android:layout_height="wrap_content"/>
    </LinearLayout>
    

    ListViewItem.axml

    <?xml version="1.0" encoding="utf-8"?>
      <TextView xmlns:android="http://schemas.android.com/apk/res/android"
            android:id="@+id/label"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="30px" />
    
  • MabroukMabrouk USMember ✭✭✭

    Friend @JBeck ,
    Yes, thats why i made a note that : the code is not perfect ;)

Sign In or Register to comment.