How To Assign Custom Object To Spinner?

CodeMonkeyCodeMonkey GBMember ✭✭✭

Hi all

I am trying to assign a list of objects to a Spinner control so that I can get the selected object details once the user has completed a form. I have this code so far which works, but I'm only able to add a String object:

ArrayAdapter cityAdapter = new ArrayAdapter(this, Android.Resource.Layout.SimpleSpinnerItem);

                             cityAdapter.SetDropDownViewResource(Android.Resource.Layout.SimpleSpinnerDropDownItem);

                             foreach (City item in citys)
                             {

                                 cityAdapter.Add(item.CityName);
                             }

How can I make a call like cityAdapter.Add(myCustomObject) and then set which property the Spinner displays?

Any help appreciated.

Posts

  • CheesebaronCheesebaron DKInsider, University mod

    You need to make your own adapter in order to choose which property to display. You can simply inherit from ArrayAdapter and override GetView and GetDropDownView which can return whatever View you want to display in the Spinner.

  • JonathanPryorJonathanPryor USXamarin Team Xamurai

    You could use the ArrayAdapter<T> type instead of just ArrayAdapter. However, unless City is a Java.Lang.Object subclass, this will require additional use of grefs (one per ArrayAdapter entry). I would instead recommend subclassing BaseAdapter<T>.

  • CodeMonkeyCodeMonkey GBMember ✭✭✭

    Thanks for the info guys, I will try implement my custom Adapter tomorrow and update.

  • CheesebaronCheesebaron DKInsider, University mod
    edited November 2012

    I have a custom adapter for a spinner in one of my apps, which looks like this:

    using System.Collections.Generic;
    using System.Linq;
    
    using Android.App;
    using Android.Views;
    using Android.Widget;
    
    using BK.EMS.NSP.Model;
    
    namespace NSPublic.AndroidClient.Adapters
    {
        public class UpdateFreqAdapter : BaseAdapter, ISpinnerAdapter
        {
            private readonly Activity _context;
            private readonly UpdateFrequencyCollectionViewModel _collectionViewModel;
            private readonly IList<View> _views = new List<View>();
    
            public UpdateFreqAdapter(Activity context, UpdateFrequencyCollectionViewModel data)
            {
                _context = context;
                _collectionViewModel = data;
            }
    
            public UpdateFrequencyViewModel GetItemAtPosition(int position)
            {
                return _collectionViewModel.ElementAt(position);
            }
    
            public override Java.Lang.Object GetItem(int position)
            {
                return null;
            }
    
            public override long GetItemId(int id)
            {
                return id;
            }
    
            public override int Count
            {
                get
                {
                    return _collectionViewModel == null ? 0 : _collectionViewModel.Count();
                }
            }
    
            public override View GetDropDownView(int position, View convertView, ViewGroup parent)
            {
                return GetCustomView(position, convertView, parent, true);
            }
    
            public override View GetView(int position, View convertView, ViewGroup parent)
            {
                return GetCustomView(position, convertView, parent, false);
            }
    
            private View GetCustomView(int position, View convertView, ViewGroup parent, bool dropdown)
            {
                var item = _collectionViewModel.ElementAt(position);
    
                var inflater = LayoutInflater.From(_context);
                var view = convertView ?? inflater.Inflate((dropdown ? Resource.Layout.SpinnerItemDropdown : Resource.Layout.SpinnerItemText), parent, false);
    
                var text = view.FindViewById<TextView>(Resource.Id.text);
    
                if (text != null)
                    text.Text = item.Frequency >= 30 ? "Off" : item.Text;
    
                if (!_views.Contains(view))
                    _views.Add(view);
    
                return view;
            }
    
            private void ClearViews()
            {
                foreach (var view in _views)
                {
                    view.Dispose();
                }
                _views.Clear();
            }
    
            protected override void Dispose(bool disposing)
            {
                ClearViews();
                base.Dispose(disposing);
            }
        }
    }
    

    The UpdateFrequencyCollectionViewModel is just an ObeservableCollection of a model class, you could pass your own list here.

    And the inflated XML is:

    SpinnerItemDropdown.axml

    <?xml version="1.0" encoding="utf-8"?>
    <CheckedTextView 
      android:id="@+id/text" 
      style="?android:attr/spinnerDropDownItemStyle" 
      android:singleLine="true" 
      android:layout_width="fill_parent" 
      android:layout_height="?android:attr/listPreferredItemHeight" 
      xmlns:android="http://schemas.android.com/apk/res/android"
      />
    

    SpinnerItemText.axml

    <?xml version="1.0" encoding="utf-8"?>
    <TextView
      xmlns:android="http://schemas.android.com/apk/res/android"
      android:id="@+id/text"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:padding="10dp"
      android:textSize="16sp"
      android:textColor="#000000"
      />
    
  • sandroherbstsandroherbst BRMember ✭✭

    Hi Chesebaron,

    I tried to use your code without success...

    I´m trying to use spinner with sqlite with ORM

    Do you have an example of a Spinner with sqlite?

    Thanks,

    Sandro Herbst

  • CodeMonkeyCodeMonkey GBMember ✭✭✭

    @sandroherbst The code Cheesebaron supplied is just the adaptor for a spinner, so before creating this adaptor you should already have pulled the data from your sqlite database. Once you have the data you pass it into the adaptor when initializing it, see this constructor:

    public UpdateFreqAdapter(Activity context, UpdateFrequencyCollectionViewModel data)

    So here UpdateFrequencyCollectionViewModel is the data to be shown in the spinner, but you can pass any type of data into the adaptor you create.

    Can you successfully query your database for data?

  • sandroherbstsandroherbst BRMember ✭✭

    Hi @CodeMonkey, I'm using ORM to query my database, and it's ok.

    I've chenaged the Cheesebaron code to my Customer class and the project compiles well, but I don't know how to call it...

    Could you help me?

  • sandroherbstsandroherbst BRMember ✭✭

    Hi @CodeMonkey, after a long Google Search, I've made @Chesebaron code work's for my project.

    Now I can show and select the customer list in a my order.

    The problem now is when I edit an order, how can I programatically select the customer in the spinner?

  • StevaSteva RSMember ✭✭✭
    _spinner.SetSelection(position); 
    

    ?

  • pawan.4190pawan.4190 USMember

    How to Get the data in Spinner?
    I want to get all the Group Names from DB. I write simple Sql Query and and the result in list object and pass to adpater of spinner.
    i was trying bt it gets only "DemoApp.Group" in Spinner.

Sign In or Register to comment.