On Sep 18, 2012, at 10:32 AM, hugoterelle <[email protected]> wrote:
> I have a problem using the Android "Spinner". I put an objects collection
> into that component:
>
> List<Article> myList = ... ;
>
> var sp = View.FindViewById<Spinner>(id);
> var adapter = new ArrayAdapter<Article>(View.Context,
> Android.Resource.Layout.SimpleSpinnerItem);
> adapter.AddAll(myList);
> sp.Adapter = adapter;
Article is NOT a Java.Lang.Object. As such, your `adapter.AddAll()` call will
need to create a java.lang.Object "wrapper" for each instance in `myList`;
http://lists.ximian.com/pipermail/monodroid/2012-August/011730.html
> If you were dealing with some other type, specifically a managed type, you'd
> want to consider forgoing ArrayAdapter<T> altogether and using BaseAdapter<T>
> instead. This will cause item lookup to be _slower_ (due to the transition to
> managed code), but gref counts will also be lower and there will be fewer
> instances allocated.
Meanwhile...
> When the user choose the right object (displayed thanks the ToString() method
> of Article), I try to get back the selected object with:
>
> var sp = View.FindViewById<Spinner>(id);
> Article myArticle;
> myArticle = (Article)(object)sp.SelectedItem;
Spinner.SelectedItem returns a Java.Lang.Object. Since Article isn't a
Java.Lang.Object, Spinner.SelectedItem will be returning the wrapper instance,
not your Article instance. I suspect that if you did:
Console.WriteLine (sp.SelectedItem.GetType ());
you'd see that `sp.SelectedItem` was an Android.Runtime.JavaObject instance.
There's an indirection going on, part of which was implicit because you're
using ArrayAdapter<T>. To get back your original instance, you need to instead
use the Adapter:
myArticle = ((ArrayAdapter<Article>)sp.Adapter).GetItem
(sp.SelectedItemPosition);
As mentioned in the above email thread, you may want to forgo ArrayAdapter and
instead provide your own BaseAdapter<T>, in which case you'd still want to use
Spinner.SelectedItemPosition + YourAdapter.GetItem(int), though you'd need to
change the type used in the cast.
- Jon
_______________________________________________
Monodroid mailing list
[email protected]
UNSUBSCRIBE INFORMATION:
http://lists.ximian.com/mailman/listinfo/monodroid