Android:将迭代值传递给onItemSelectedListener

时间:2014-08-04 03:37:34

标签: android closures programmatically-created onitemselectedlistener

您好我正在根据用户选择动态创建微调器列表。这里我也为每个微调器实现了OnItemSelectedListener,因为我想知道多个微调器当前正在访问哪个微调器的方法。这是代码,

     for (int i = 0; i < count; i++) {
        ArrayList<String> spinnerArray = new ArrayList<String>();
        spinnerArray.add("one");
        spinnerArray.add("two");
        spinnerArray.add("three");
        spinnerArray.add("four");
        spinnerArray.add("five");

        Spinner spinner = new Spinner(this);

        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View view,
                    int position, long id) {

                Object item = parent.getItemAtPosition(position);
                Log.d("vij-debug", "selector1 no is " + item);
                Log.d("vij-debug", "selector1 id is"+ view.getId());

                 //medicineArray1[i][1]=(String)item;
                // here I want to access the iteration value i



            }

            public void onNothingSelected(AdapterView<?> parent) {
            }
        });

        ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(
                this, android.R.layout.simple_spinner_dropdown_item,
                spinnerArray);
        spinner.setAdapter(spinnerArrayAdapter);

有人能提出合适的解决方案吗?

2 个答案:

答案 0 :(得分:1)

在创建时将Spinner标记设置为i,然后从AdapterView<?> parent中的onItemSelected()参数中检索它。

Spinner spinner = new Spinner(this);
spinner.setTag(i);
...
spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener()
    {
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id)
        {
            int spinnerNumber = parent.getTag();
        }
        ...
    }
);

答案 1 :(得分:0)

您可以使用List并将旋转器存储在那里。在你的for循环中

//inside for loop
List<Spinner> spinnerList=new ArrayList<Spinner>();
Spinner spinner = new Spinner(this);
spinnerlist.add(spinner);

//end

//outside for loop
for(int i=0;i<spinnerList.size();i++){

setListenerToSpinner(spinnerList.get(i));

}

//end


//function
public void setListenerToSpinner(Spinner spinner){

spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            public void onItemSelected(AdapterView<?> parent, View view,
                    int position, long id) {

                Object item = parent.getItemAtPosition(position);
                Log.d("vij-debug", "selector1 no is " + item);
                Log.d("vij-debug", "selector1 id is"+ view.getId());

                 //medicineArray1[i][1]=(String)item;
                // here I want to access the iteration value i

            }

}