我有一个简单的Spinner
实现为:
vehicle = json.getJSONArray("vehicle");
for(int i = 0; i < vehicle.length(); i++){
JSONObject c = vehicle.getJSONObject(i);
//put json obkject on variable
String id = c.getString("id");
String name = c.getString("name");
String capacity = c.getString("capacity");
String cost = c.getString("cost");
String v = name + " ("+capacity + " Liters)";
vehicleList.add(v);
// Set Spinner Adapter
mySpinner.setAdapter(new ArrayAdapter<String>(OrderDetails.this,android.R.layout.simple_spinner_dropdown_item,vehicleList));
// Spinner on item click listener
mySpinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> arg0,View arg1, int position, long arg3) {
car = vehicleList.get(+position);
Toast.makeText(getApplicationContext(), car, Toast.LENGTH_SHORT).show();
}
@Override
public void onNothingSelected(AdapterView<?> arg0) {
car = null;
}
});
}
我想在car变量中获取“ID”的值。是否可以通过上述实施?
提前致谢。
答案 0 :(得分:1)
尝试用这个替换你的项目点击监听器......
mySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {
public void onItemSelected(AdapterView<?> arg0, View view,
int position, long id) {
int spinnerItem = spinner.getSelectedItemPosition();
car = vehicleList.get(spinnerItem);
Toast.makeText(getApplicationContext(), selectedId, Toast.LENGTH_SHORT).show();
}
public void onNothingSelected(AdapterView<?> arg0) {
// nothing to do here :|
}
});
<强> //修改 您可以创建另一个包含ID值的列表...然后将值添加为vehicleList ...
idList.add(id);
然后在spinner中选择项目时调用
String selectedId = idList.get(spinnerItem);
答案 1 :(得分:0)
返回所选位置。
mySpinner.getSelectedItem()
或
mySpinner.getSelectedItemPosition()