OnClickListener()在最后一个Spinner的元素上

时间:2013-12-21 19:36:30

标签: java android

我有来自ArrayList(工作清单)的Spinner(SpinnerP)。工作清单中的最后一个要素是“添加”

ArrayAdapter<String> dataAdapter = new ArrayAdapter<String>(this, R.layout.spinneritem, worklist);
         dataAdapter.setDropDownViewResource(R.layout.custom_spinner);
         SpinnerP.setAdapter(dataAdapter);

Spinner工作正常,但我需要为Spinner中的最后一个元素创建类似onClickListener的东西。这将是对Spinner的行动。我怎么能这样做?

当我使用Spinner.setOnItemSelectedListener(new OnItemSelectedListener()时,我有2个错误

Multiple markers at this line
    - OnItemSelectedListener cannot be resolved to a type
    - The method setOnItemSelectedListener(AdapterView.OnItemSelectedListener) in the type AdapterView<SpinnerAdapter> is not applicable for the 
     arguments (new OnItemSelectedListener(){})

3 个答案:

答案 0 :(得分:1)

设置onItemSelectedListener,然后检查是否是该项目。例如:

Spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

        public void onItemSelected(AdapterView<?> arg0, View arg1,
                int arg2, long arg3) {

                String selectedValue = arg0.getItemAtPosition(arg2).toString();

                if(selectedValue.equals("add")){
                          // add item to spinner
                }

        @Override
        public void onNothingSelected(AdapterView<?> arg0) {
            // TODO Auto-generated method stub

        }
    });    

您需要像这样导入onItemSelectedListener

import android.widget.AdapterView.OnItemSelectedListener;

答案 1 :(得分:0)

spinner.setOnItemSelectedListener(new OnItemSelectedListener(){                     @覆盖                     public void onItemSelected(AdapterView parentView,View selectedItemView,int position,long id){                          //在这里检查,它是否是最后一项,然后采取行动。     如果((worklist.size() - 1)==位置)     {     }                     }

                @Override
                public void onNothingSelected(AdapterView<?> parentView) {
                    // your code here
                }

            });

答案 2 :(得分:0)

接受的答案确实有效,但我认为检查所选项目的字符串值是否是最后一项的字符串并不干净。 AdapterView提供方法getCount(),该方法返回项目总数。现在,您可以检查所选项目的位置(当然是+1)是否与总计数相符:

    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
            if(parent.getCount() == position + 1) {// last item
                // your code here
            }
        }

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

        }
    });