我有一个列表:
[{
"catid": 1,
"title": "windows"
},
{
"catid": 2,
"title": "Android",
}
]
我想在微调器中显示列表标题。 当用户选择标题时,变量(int)selected_item等于相应的catid。 例如,当用户从微调器中选择标题“ Android”时,(int)selected_item = 2;
public void setupcatspinner(ArrayList<String> titles,ArrayList<Integer> catids){
final Spinner s1 = findViewById(R.id.spinner);
ArrayAdapter<String> adap=new ArrayAdapter<>
(this, android.R.layout.simple_spinner_item, titles);
adap.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
s1.setAdapter(adap);
s1.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
// (int)selected_item = ???
}
@Override
public void onNothingSelected(AdapterView<?> parent) {
}
});
}
答案 0 :(得分:0)
因此,selected_item = titles.get(position).get(0)
假定二维列表catid
的索引titles
为0。
答案 1 :(得分:0)
您可以维护两个不同的列表,一个用于ID,另一个用于标题。将OnItemSelectedListener
设置为spinner,您将获得所选项目的位置,并从catId列表中获得相应的ID。
检查下面的代码,
// List containing all category ids
ArrayList<String> catIdList = new ArrayList<>();
// List containing all titles
ArrayList<String> titleList = new ArrayList<>();
// Store the data in respective lists
JSONArray jsonArray = new JSONArray(data);
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject = jsonArray.getJSONObject(i);
if(jsonObject.has("catid")){
catIdList.add(jsonObject.getString("catid"));
}
if(jsonObject.has("title")){
titleList.add(jsonObject.getString("title"));
}
}
您可以将titleList
传递给SpinnerAdapter
。
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
@Override
public void onItemSelected(AdapterView<?> adapterView, View view, int position, long l) {
String catId = catIdList.get(position);
String title = titleList.get(position);
}
@Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
});