1

Im trying to create a spinner containing usernames and userIDs. I only want to display the username and not the userID. But when a user is selected i would like to find out what the userID is of that user. Im using unique identifier IDs for the userIDs.

Help would be most appreciated, thank you.

EDIT: Solved! I simply keep an array with IDs with the same order as the spinner

Erik
  • 117
  • 3
  • 15
  • voting to re-open as this is monodroid/xamarin.android and not java. While the process might be very similar it's *not* the same. – Andras Zoltan Jun 12 '13 at 13:06

1 Answers1

2

You can make custom adapter for your spinner:

public class CustomSpinnerAdapter : BaseAdapter
{
    readonly Activity _context;
    private List<Users> _items;
    public ComboBoxAdapter(Activity context, List<Users> listOfItems)
    {
        _context = context;
        _items = listOfItems;
    }

    public override int Count
    {
        get { return _items.Count; }
    }

    public override Java.Lang.Object GetItem(int position)
    {
        return position;
    }

    public override long GetItemId(int position)
    {
        return position;
    }

    public override View GetView(int position, View convertView, ViewGroup parent)
    {
        var item = _items[position];
        var view = (convertView ?? context.LayoutInflater.Inflate(Android.Resource.Layout.SimpleSpinnerDropDownItem,
            parent,
            false));
        var name = view.FindViewById<TextView>(Android.Resource.Id.Text1);
        name.Text = item.Name;
        return view;
    }

    public Users GetItemAtPosition(int position)
    {
        return _items[position];
    }
}

Also you need to make class that contains information about users:

public class Users
{
  int Id{get;set;}
  string Name{get;set;}
}

Then you can create and populate your spinner with data:

[Activity(Label = "Spinner Activity")]
public class SpinnerActivity : Activity
{
    private List<Users> _users;
    protected override void OnCreate(Bundle bundle)
    {
        base.OnCreate(bundle);

        SetContentView(Resource.Layout.LayoutWithSpinner);
        var spinner = FindViewById<Spinner>(Resource.Id.spinner);
        //you need to add data to _users before creating adapter
        var adapter = new CustomSpinnerAdapter(this,_users);
        spinner.Adapter = adapter;
        spinner.ItemSelected += SpinnerItemSelected;
    }

    private void SpinnerItemSelected(object sender, AdapterView.ItemSelectedEventArgs e)
    {
        Toast.MakeText(this, "Id:"+_users[e.Position].Id +" Name"+_users[e.Position].Name, ToastLength.Long).Show();
    }
}
4x2bit
  • 82
  • 6