在微调器中使用二维列表

时间:2018-09-30 15:37:50

标签: android

我有一个列表:

[{    
    "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) {

        }
    });

}

2 个答案:

答案 0 :(得分: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) {

        }
    });