android:为spinner视图添加唯一标记或id

时间:2015-02-10 19:52:12

标签: android spinner android-spinner

我在我的应用程序中创建了4个微调视图,当我在其中一个上更改所选项目时,我想知道选择和更改了哪个微调器。我使用这段代码:

for(int i=0;i<4;i++){
final Spinner spinner= new Spinner(context);
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_dropdown_item, spinnerArray);
                spinner.setAdapter(spinnerArrayAdapter);

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

                        }
                    }

                    @Override
                    public void onNothingSelected(AdapterView<?> adapterView) {

                    }
                });}

如何为每个微调器设置唯一标记并在ItemSelectedListner上返回此标记? 感谢

2 个答案:

答案 0 :(得分:1)

这样做:

 for(int i=0;i<4;i++){
   final Spinner spinner= new Spinner(context);
   spinner.setTag(i);
   ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_dropdown_item, spinnerArray);
            spinner.setAdapter(spinnerArrayAdapter);

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

                       if (parent.getTag().equals("0")){
                          //your code
                             }
                       else if (parent.getTag().equals("1")){
                          //your code
                              }

                    }
                }

                @Override
                public void onNothingSelected(AdapterView<?> adapterView) {

                }
            });}

答案 1 :(得分:0)

在onItemSelected()中使用parent.getId()来获取其项目被选中的微调器的Id。工作代码:

for(int i=0;i<4;i++){


final Spinner spinner= new Spinner(context);
   spinner.setId(i);
   ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_spinner_dropdown_item, spinnerArray);
            spinner.setAdapter(spinnerArrayAdapter);

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

                   switch(parent.getId()){
case "0": //your code
case "1": //your code
...
}

                }
            }

            @Override
            public void onNothingSelected(AdapterView<?> adapterView) {

            }
        });