这里给大家提供下绑定 spinner键值对的方法。
首先创建绑定模型BaseItem
public class BaseItem { public BaseItem(Integer id,String value){ this.setId(id); this.setValue(value); } private Integer id; private String value; public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getValue() { return value; } public void setValue(String value) { this.value = value; } //必须要重写,不然绑定spinner会有问题 @Override public String toString() { // TODO Auto-generated method stub return value; }}
接着,我封装了绑定Spinner的方法。
因为许多地方要用,所以就偷懒一下,做成一个方法了。
public class ControlHelper { public static下面是我的实现:在MainActivity中void BindSpinner(Context context, T control, List list) { ArrayAdapter adapter=new ArrayAdapter (context, android.R.layout.simple_list_item_1,list); ((T)control).setAdapter(adapter); } public static void BindSpinner(Context context, T control, List list,Integer layout) { ArrayAdapter adapter=new ArrayAdapter (context, layout,list); ((T)control).setAdapter(adapter); }}
//region 读取仓库列表 //Spinner @SuppressLint("HandlerLeak") Handler handler1 = new Handler() { @Override public void handleMessage(Message msg) {//这里句简略了,绑定BaseItem List最后在onCreate中调用list=new ArrayList<>(); BaseItem item = new BaseItem(wid,name); list.add(item); }//将BaseItem绑定到Spinner BindSpinner.Bind(getBaseContext(),spinner,list); } }; //读取仓库列表 public void GetWarehouseAll(){ new Thread(new Runnable() { @Override public void run() { try {//获取Spinner数据(webapi) String json = HttpWebapi.DoPost("/webapi/GetWarehouseAll", new ArrayList ()); Message msg = Message.obtain(); msg.obj = json; handler1.sendMessage(msg); } catch (Exception e) { e.printStackTrace(); } } }).start(); } //endregion
//读取仓库列表 GetWarehouseAll(); //绑定了一个选中事件(用来测试) spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() { public void onItemSelected(AdapterView parent, View view, int position, long id) { /* * ids是刚刚新建的list里面的ID */ int ids = ((BaseItem) spinner.getSelectedItem()).getId(); System.out.println(ids); Toast.makeText(getApplicationContext(), String.valueOf(ids), Toast.LENGTH_LONG).show(); } @Override public void onNothingSelected(AdapterView adapterView) { } });