Load Array string to Listview in Andriod using c#

In this tutorial I will show you how to bind array to a string using an ArrayAdapter to listview in android apps using c sharp with Xamarin.




Follow these steps to display an array of string in a listivew.
   v  Create new Project



    v  Expand resource folder

      v    Click on layout folder  as shown below image
               v  Open  layout  Main.axml   and paste below code
<?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:text=Load Data
        android:layout_width=match_parent
        android:layout_height=wrap_content
        android:id=@+id/button1 />
    <ListView
        android:minWidth=25px
        android:minHeight=25px
        android:layout_width=match_parent
        android:layout_height=match_parent
        android:id=@+id/listView1 />
</LinearLayout>
   

v     Open MainActivity.cs

    In MainActivity create two event one button click event and another Listview item click.overriding ItemClick allows us to handle item selection.


  public class MainActivity : Activity
    {
        Button btnclick;
        private List<string> mitem;
        private ListView mlistview;
        protected override voidOnCreate(Bundle bundle)
        {
            base.OnCreate(bundle);
            // Set our view from the “main” layout resource
             SetContentView (Resource.Layout.Main);
            btnclick = FindViewById<Button>(Resource.Id.button1);
            mlistview = FindViewById<ListView>(Resource.Id.listView1);
          
            btnclick.Click += btn_Click;
             
            mlistview.ItemClick += List_Click;
        }
        private voidList_Click(object sender, AdapterView.ItemClickEventArgs e)
        {
             Toast.MakeText(this,mitem[e.Position].ToString(),ToastLength.Short).Show();
        }
        private voidbtn_Click(object sender, EventArgs e)
        {
            mitem = new List<string>();
            mitem.Add(“Computer”);
            mitem.Add(“Keyboard”);
            mitem.Add(“Mouse”);
            mitem.Add(“Harddisk”);
            mitem.Add(“Monitor”);
         ArrayAdapter adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleExpandableListItem1, mitem);
            mlistview.Adapter = adapter;
           
        }
    }




Leave a Reply

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