[mono-android] creating adapter from resource
Jonathan Pryor
jpryor at novell.com
Sun Mar 27 10:32:41 EDT 2011
On Mar 27, 2011, at 9:28 AM, John Murray wrote:
> So can anyone tell me why the first of these doesn’t work but the second does
...
>
> Simple approach which doesn’t work
> airfadapter =new ArrayAdapter(this, Resource.Layout.list_item, Resource.Array.GBairfarr1);
> depfield.Adapter = airfadapter;
The corresponding documentation:
http://developer.android.com/reference/android/widget/ArrayAdapter.html#ArrayAdapter(android.content.Context, int, int)
Thus, for the ArrayAdapter(Context context, int resource, int textViewResourceId), the textViewResourceId is:
"The id of the TextView within the layout resource to be populated."
In other words, it's _not_ the array to use to populate the adapter, it's a resource id _within_ `resource` that contains the TextView to fill.
So it doesn't work because it doesn't do what you thought it did. :-)
> But this works
> Android.Widget.ArrayAdapter<string> adapter = new ArrayAdapter<string>(this,Resource.Id.wtv2);
> List<string> arr3 = new List<string>();
> arr3 = (from s in Resources.GetStringArray(Resource.Array.airfarr1) select s).ToList();
> foreach (var s in arr3)
> {
> if (s.Substring(0,2)=="EG")
> {
> adapter.Add(s);
> }
> }
> depfield.Adapter = adapter;
>
> //the above foreach loop was only inserted t filter the list and has no significance in this
> //other than it serves as a means for getting a list into an android adapter
>
>
> Ps is there some easy way to convert a System.collection.list to an android.widget.arrayadapter
There is an ArrayAdapter<T>(Context, int, IList<T>) constructor and an ArrayAdapter<T>(Context, int, T[]) constructor:
http://docs.mono-android.net/index.aspx?link=T%3aAndroid.Widget.ArrayAdapter`1%2f*
Thus, you should be able to do:
var adapter = new ArrayAdapter<string>(this, Resource.Id.wtv2, Resources.GetStringArray(Resource.Array.airfarr1));
or:
var adapter = new ArrayAdapter<string>(this, Resource.Id.wtv2,
Resources.GetStringArray(Resource.Array.airfarr1).Where(s => s.StartsWith ("EG")).ToList());
- Jon
More information about the Monodroid
mailing list