如何获得动态微调器选择的数组中的项目ID?

时间:2018-07-04 06:12:08

标签: java android arrays android-spinner

我完美地创建了动态微调器,如下所示

        k++;
        flag=k;
        final LinearLayout.LayoutParams lparams = new 
        LinearLayout.LayoutParams(380,120);
        lparams.setMargins(1, 20, 1, 0);
        colorSpinner[flag] = new Spinner(getActivity());
        colorSpinner[flag].setLayoutParams(lparams);
        colorSpinner[flag].setId(flag);
        colorSpinner[flag].setAdapter(new ArrayAdapter<String>(getContext(), android.R.layout.simple_spinner_dropdown_item, color_list));

        loadColorSpinnerData(URL);

        colorSpinner[flag].setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l)
            {
                color_id = datalist1.get(i).getId();
            }
            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {
                // DO Nothing here
            }
        });

mLayout.addView(colorSpinner[flag]);

color_array.add(colorSpinner[flag]);

如何获取数组中的颜色ID

这不行

String[] Acolorid = new String[color_array.size()];
    for(int i = 0; i < color_array.size(); i++){
        Acolorid[i] = String.valueOf(color_array.get(i).getSelectedItemPosition()+1); //Acolorid[j]= String.valueOf(color_id);//color_array.get(i).getSelectedItem().toString();
        Hcolorid=String.join(",",Acolorid);
    }

请给我我想获取数组中颜色ID而不获取项目位置的解决方案。

1 个答案:

答案 0 :(得分:1)

执行此操作的一种方法是使用View.setTag()存储以后要检索的数据。像这样:

     public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l)
        {
            // get some data related to the selected item
            color_id = datalist1.get(i).getId();
            // attach it to the spinner
            adapterView.setTag(color_id);
        }
        @Override
        public void onNothingSelected(AdapterView<?> adapterView) {
            // DO Nothing here
        }

稍后检索:

String[] Acolorid = new String[color_array.size()];
    for(int i = 0; i < color_array.size(); i++){
        // get the saved data
        Object data = color_array.get(i).getTag();
        if (data != null) {
            Acolorid[i] = data.toString();
        }
    }
    Hcolorid=String.join(",",Acolorid);