Android Spinner 绑定键值对

时间:2023-03-09 16:11:31
Android Spinner 绑定键值对

这里给大家提供下绑定 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 <T extends AdapterView> void BindSpinner(Context context, T control, List<BaseItem> list)
{
ArrayAdapter<BaseItem> adapter=new ArrayAdapter<BaseItem>(context, android.R.layout.simple_list_item_1,list);
((T)control).setAdapter(adapter);
}
public static <T extends AdapterView> void BindSpinner(Context context, T control, List<BaseItem> list,Integer layout)
{
ArrayAdapter<BaseItem> adapter=new ArrayAdapter<BaseItem>(context, layout,list);
((T)control).setAdapter(adapter);
}
}

下面是我的实现:在MainActivity中

//region 读取仓库列表
//Spinner
@SuppressLint("HandlerLeak")
Handler handler1 = new Handler() {
@Override
public void handleMessage(Message msg) {
//这里句简略了,绑定BaseItem
List<BaseItem> 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<NameValuePair>());
Message msg = Message.obtain();
msg.obj = json;
handler1.sendMessage(msg);
} catch (Exception e) {
e.printStackTrace();
} }
}).start();
}
//endregion

最后在onCreate中调用

//读取仓库列表
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) { } });