A simple way to show listview in Android using Xamarin
May 14, 2015
2 comments
Article
Ways to do it
There are basically 2 ways to do it in Android.
- Using the Listview control
- Using the ListActivity
By using ListActivity
In this way we don’t need to define any Listview in our AXML page. Just few lines of code will do it.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
[Activity(Label = "ListviewDemo", MainLauncher = true, Icon = "@drawable/icon")] public class MainActivity : ListActivity { int count = 1; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); string[] earthquakePlaces = new string[] { "Nepal", "Solomon Sea", "Papua New Guinea", "Nepal", "Taiwan", "Papua New Guinea" , "Flores Sea", "Mid-Atlantic range"}; ListAdapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleListItem1, earthquakePlaces); } } |
By adding Listview control
The way is very much similar. We need a ListAdapter to fill the ListView. The extra step we need to do is to add a ListView control to our AXML page.
AXML Page code
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
<?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical" android:layout_width="fill_parent" android:layout_height="fill_parent" android:minWidth="25px" android:minHeight="25px"> <ListView android:minWidth="25px" android:minHeight="25px" android:layout_width="match_parent" android:layout_height="match_parent" android:id="@+id/lvwEarthquakes" /> </LinearLayout> |
Design mode view of the above AXML
Let’s add the code to the Activity
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
[Activity(Label = "ListviewDemo", MainLauncher = true, Icon = "@drawable/icon")] public class MainActivity : Activity { int count = 1; protected override void OnCreate(Bundle bundle) { base.OnCreate(bundle); // Set our view from the "main" layout resource SetContentView(Resource.Layout.Main); string[] earthquakePlaces = new string[] { "Nepal", "Solomon Sea", "Papua New Guinea", "Nepal", "Taiwan", "Papua New Guinea" , "Flores Sea", "Mid-Atlantic range"}; ListView lvw = FindViewById<ListView>(Resource.Id.lvwEarthquakes); lvw.Adapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleListItem1, earthquakePlaces); } } |
Now, we are ready with our simple Listview in Android.
Hope that help. Happy coding 🙂
Categories: Android, CSharp, Visual Studio, Xamarin