包含用户名和用户ID的微调器,只有用户名可见

时间:2012-08-22 11:46:52

标签: c# xamarin.android android-spinner

我正在尝试创建一个包含用户名和用户ID的微调器。我只想显示用户名而不是userID。但是当选择用户时,我想知道该用户的userID是什么。我使用唯一标识符ID作为用户ID。

非常感谢帮助,谢谢。

编辑:解决了!我只是保留一个ID为与spinner

顺序相同的数组

1 个答案:

答案 0 :(得分:2)

您可以为您的微调器创建自定义适配器:

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];
    }
}

此外,您还需要创建包含用户信息的类:

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

然后,您可以使用数据创建和填充微调器:

[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();
    }
}